简体   繁体   中英

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?

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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