Reputation: 9959
My Product class is
public class Product
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ProductID { get; set; }
public string ProductName { get; set; }
public virtual ICollection<ProductColor> ProductColors { get; set; }
}
The Color class
public class Color
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ColorID { get; set; }
public string ColorName { get; set; }
public virtual ICollection<ProductColor> ProductColors { get; set; }
}
and the intermediate class for creating many to many relationship
public class ProductColor
{
public int ProductID { get; set; }
public int ColorID { get; set; }
public virtual Product Product { get; set; }
public virtual Color Color { get; set; }
}
Supposing my product model contains
ProductID ProductName
1 Product 1
2 Product 2
3 Product 3
My color model contains
ColorID ColorName
1 Red
2 Green
3 Blue
And the intermediate model contains
ProductID ColorID
1 1
1 2
2 3
How can i write a Linq query to get all the colors for each Product in a list?
Upvotes: 1
Views: 1608
Reputation: 9959
Ok. This is what i was looking for
var Colors = context.Products.SelectMany(p => p.Colors);
and filtering by ProductID
var Colors = context.Products.Where(p => p.ProductID == 1).SelectMany(p => p.Colors);
Upvotes: 0
Reputation: 1816
This should do what you need:
var res = Products.Select(s => new{ Product = s, Colors = s.ProductColors.Select(m => m.Color) }).ToList();
This will produce anonymous type with two properties: Product
and array of Color
s that this product has.
Or you can remove ProductColor
entity, change Product
to:
public class Product
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ProductID { get; set; }
public string ProductName { get; set; }
public virtual ICollection<Color> Colors { get; set; }
}
Color
to:
public class Color
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ColorID { get; set; }
public string ColorName { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
And then you will have already Product
s with their Color
s.
Upvotes: 2