Question

I am fairly new to ORMs and ADO.NET EF in particular. I'm using the Code First approach. I have these two tables in my DB :

Material:

public class Material
    {
        [Required]
        [MaxLength(10)]
        public string Code { get; set; }


        [MaxLength(40)]
        public string Color { get; set; }

        [MaxLength(40)]
        public string Description { get; set; }

        [MaxLength(255)]
        public string Picture { get; set; }

        public long MaterialTypeId { get; set; }
        public virtual MaterialType MaterialType { get; set; }

    }

and MaterialType :

public class MaterialType 
  { 
      [MaxLength(40)] 
      public string MatType { get; set; }

      public virtual ICollection<Material> Materials { get; set; }
  }

And I have a DataGridView where I populate with all the info from Material except MatType which is Leather, Plastic and stuff like that and which I have to take from the MaterialType table. It's the only FK so far so I've user SELECT *.. before and now when it comes to it I don't know how to construct my code/query so I can populate the DataGridView with the info from the second table. In the DataGridView I have the column MaterialTypeId which is hidden.

Was it helpful?

Solution

Use DataTransferObjects(DTO).

public class MaterialDTO
{
        public string Code { get; set; }

        public string Color { get; set; }

        public string Description { get; set; }

        public string Picture { get; set; }

        public string MatType { get; set; }
}

Then complete it with info:

List<MaterialDTO> listForGrid = context.Material.Select(e=>new MaterialDTO(){Code=e.Code, Color = e.Color, Description = e.Description, Picture = e.Picture, MatType = e.MaterialType.MatType}).ToList();

This example gets whole data from the DB from Table Material, and puts it to List<MaterialDTO> listForGrid. Maybe you will also want to put Where before the Select, to take only part of data from the table but not the whole table.

Then bind this data to Grid...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top