简体   繁体   中英

Linq to entities group by many to many

I have 3 entities, with a many/many relationship:

Products -< Products_vehicles >- Vehicles

1 product can have many vehicles

1 vehicle can have many products

As with all many/many relationships the products_vehicles class is hidden and is shown as navigation properties on the entities by EF So my classes look like this:

public partial class product
    public int id { get; set; }
    public string part_name { get; set; }
    public virtual ICollection<vehicle> vehicles { get; set; }

 public partial class vehicle
{
    public int id { get; set; }
    public string make { get; set; }
    public string model { get; set; }
    public virtual ICollection<product> products { get; set; }

I can get the products and all related vehicles easily

I wish to group the products by the make, model of the vehicle, so my output would look something like this:

product id: 5 part_name: door make: ford model: focus

product id: 5 part_name: door make: saab model: 9-3

Is this possible?

Update

For more clarity, here's an example:

So let's say i have a product called 'bonnet' it fits 5 different vehicles:

  • Ford Focus 1.6L
  • Ford Fiesta 2L
  • Ford Fiesta 1.6L
  • Ford Mondeo 2L
  • Ford Mondeo 1.8L

Currently i'm getting 1 product with a collection of vehicles listing all 5 above.

I want them grouped by firstly the 'partname' (bonnet), secondly 'make' and thirdly 'model'. The results should be like:

Bonnet > Ford, Fiesta 2L

         Ford, Fiesta 1.6L

Bonnet > Ford, Mondeo 2L

         Ford, Mondeo 1.8L

Bonnet > Ford, Focus 1.6L

This would be very simple in SQL but i'm having a tough time getting my head around this in Linq.

Any help greatly appreciated

I'm guessing that what you want is retrieving flat records that have selected: product id, product part name, vehicle maker and vehicle model. If not, please ignore that answer.

return dbcontext.products.SelectMany(
    p => p.vehicles.Select(
        v => new {
            product_id = p.id,
            part_name = p.part_name,
            make = v.make,
            model = v.model
            }
        )
    );

If you don't want to repeat product data (which would be actually quite recommended) then you might use the following approach with nested vehicles array instead:

return dbcontext.products.Select(
    p => new {
        product_id = p.id,
        part_name = p.part_name,
        vehicles = p.vehicles.Select(
            v => new { make = v.make, model = v.model }
        }
    );

dbcontext.products is DbSet corresponding to products in your database; it might be called differently in your code.

Cheers~!

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