在EF中的多个列上连接多个表

时间:2017-12-19 09:46:14

标签: sql entity-framework linq linq-to-sql

尝试在EF上的多个列上连接多个表时遇到问题。

这是我的SQL查询

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

这是我在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}

但它只是不起作用,也没有我在StackOverflow上找到它的一些变种。

我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:0)

你可以使用它。

您的代码in关键字的第一行缺失。我修复了它并添加了wheregroup by部分。

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() }