![](/img/trans.png)
[英]How can I select using LINQ for an entry that contains a LIST with more than one row?
[英]How can i Select many with contains in LINQ?
我的產品類別是
public class Product
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ProductID { get; set; }
public string ProductName { get; set; }
public virtual ICollection<ProductColor> ProductColors { get; set; }
}
顏色類
public class Color
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ColorID { get; set; }
public string ColorName { get; set; }
public virtual ICollection<ProductColor> ProductColors { get; set; }
}
和建立多對多關系的中產階級
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; }
}
假設我的產品模型包含
ProductID ProductName
1 Product 1
2 Product 2
3 Product 3
我的顏色模型包含
ColorID ColorName
1 Red
2 Green
3 Blue
中間模型包含
ProductID ColorID
1 1
1 2
2 3
如何編寫Linq查詢以獲取列表中每個產品的所有顏色?
這應該可以滿足您的需求:
var res = Products.Select(s => new{ Product = s, Colors = s.ProductColors.Select(m => m.Color) }).ToList();
這將產生具有兩個屬性的匿名類型: Product
和該產品具有的Color
數組。
或者,您可以刪除ProductColor
實體,將Product
更改為:
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
為:
public class Color
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ColorID { get; set; }
public string ColorName { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
然后,您將已經擁有帶有Color
的Product
。
好。 這就是我想要的
var Colors = context.Products.SelectMany(p => p.Colors);
和按ProductID過濾
var Colors = context.Products.Where(p => p.ProductID == 1).SelectMany(p => p.Colors);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.