简体   繁体   中英

How to do Many To Many LINQ entity grouping queries?

I can see many examples on this site of the sort of queries I'm after, but I can't relate to them and how they work. I was wondering if you could help me.

I have set up my many-to-many tables and relationships with entity designer in Visual Studio.

tblQuotes
ID | QuoteNo | Date

tblItems
ID | PartNo | Desc

tblSuppliers
ID | Supplier | email

tblQIS (quotes items suppliers)
ID | SupplierID | QuoteID | ItemID

I've put some test data in and have begun to try to type this, but I think I first need to group by quoteNo then group by supplier, to get the details in the correct view.

var tblQuotes = from d in db.tblQuotes_Items_Suppliers
                    .Include(t => t.tblItems)
                    .Include(t => t.tblQuotes)
                    .Include(t => t.tblSuppliers)
                group by (d.QuoteID,d.SupplierID)
                select d;

Can anyone help me out?

you could try this:

var tblQuotes = 
    from d in db.tblQuotes_Items_Suppliers    // or tblQIS whatever the name
    group d by new
    {
        d.QuoteID,
        d.SupplierID
    }  into g
    select g;

that would give you Quotes grouped by both QuoteID and SupplierID

Update

the tblQuotes is a list (IQueryable) of grouped quotes, so you can access other entities as follow:

 var firstGroupOfQuotes = tblQuotes.First(); // will give you the first group of quotes
 var firstQuote = firstGroupOfQuotes.First(); // will give you the first quote in the first group
 var item = firstQuote.tblItems; // will give you the item of this quote
 var partNo = item.PartNo; // will give you the PartNo of this item

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