简体   繁体   English

如何在LINQ中选择许多包含?

[英]How can i Select many with contains in LINQ?

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? 如何编写Linq查询以获取列表中每个产品的所有颜色?

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. 这将产生具有两个属性的匿名类型: Product和该产品具有的Color数组。

Or you can remove ProductColor entity, change Product to: 或者,您可以删除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 to: 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; }
}

And then you will have already Product s with their Color s. 然后,您将已经拥有带有ColorProduct

Ok. 好。 This is what i was looking for 这就是我想要的

var Colors =  context.Products.SelectMany(p => p.Colors);

and filtering by ProductID 和按ProductID过滤

var Colors =  context.Products.Where(p => p.ProductID == 1).SelectMany(p => p.Colors);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM