简体   繁体   中英

Joining multiple tables on multiples columns in EF

I have problem when trying to join multiple tables on multiples columns on EF.

This is my SQL query

SELECT 
    Address,
    AddressName,
    COUNT(AddressCode) AS NumberOfAddress
FROM
    Tbl1
    INNER JOIN Tbl2
    ON Tbl1.AddressID = Tbl2.AddressID2
    INNER JOIN Tbl3 
    ON      (Tbl1.AddressID = Tbl3.AddressID
        AND Tbl2.NewId = Tbl3.NewId)
WHERE
    Tbl2.StartDate >= '2001-01-01'
GROUP BY
    Tbl2.AddressID2,
    Tbl3.AddressID

This is my query (just for the joining part) in EF:

var query = from Tbl1 DbContext.Tbl1
            join Tbl2 in DbContext.Tbl2
            on Tbl1.AddressID equals Tbl2.AddressID2 
            join Tbl3 in DbContext.Tbl3 
            on new {Tbl1.AddressID, Tbl2.NewId} equals new {Tbl3.AddressID,Tbl3.NewId}

But it just doesn't work, neither nor some of its variants I have found on StackOverflow.

How can I make it work?

You can use this.

At the first line of your code in keyword missing. I fixed it and added where and group by parts.

var query = from Tbl1 in Tbl1s
            join Tbl2 in Tbl2s
                on Tbl1.AddressID equals Tbl2.AddressID2 
            join Tbl3 in Tbl3s
                on new {Tbl1.AddressID, Tbl2.NewId} equals new {Tbl3.AddressID,Tbl3.NewId}
            where Tbl2.StartDate >= new DateTime(2001,1,1)
            group new {Tbl1, Tbl2} by new {Tbl2.AddressID2, Tbl3.AddressID} into g
            select new { 
                g.Key.AddressID2, 
                g.Key.AddressID, 
                NumberOfAddress = g.Count() }

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