使用LINQ在JOIN条件下进行AND运算

时间:2014-03-25 18:02:11

标签: c# sql linq entity-framework tsql

我最近遇到了一些看起来像这样的

的SQL代码
SELECT
    a.Id,
    b.Id,
    c.Id,
    d.Id,
    b.Name,
    d.Occupation,
FROM TableA a
JOIN TableB b ON a.Id = b.Id
JOIN TableC c ON b.Id = c.Id AND b.Name = a.Name
JOIN tableD d ON c.Id = d.Id AND c.Occupation = d.Occupation

我从来没有在相应的LINQ查询中使用像JOIN这样的ANDs(对于上下文,我使用Entity Framework和LINQ来处理所有查询)。我通常将所有的AND放在那里的子句中,如下所示:

var query = from a in dbContext.TableA
            join b in dbContext.TableB on a.Id equals b.Id
            join c in dbContext.TableC on b.Id equals c.Id
            join d in dbContext.TableD on c.Id equals d.Id
            where b.Name = a.Name
            where c.Occupation = d.Occupation
            select new
            {
                AId = a.Id,
                BId = b.Id,
                CId = c.Id,
                DId = d.Id,
                BName = b.Name,
                DOccupation = d.Occupation,
            };

我可以使用什么技术让我的LINQ查询与上面的SQL语句匹配?

1 个答案:

答案 0 :(得分:1)

您可以通过从属性构建匿名类型来加入多个属性,如下所示:

var query = from a in dbContext.TableA
            join b in dbContext.TableB on new { a.Id, a.Name } equals new { b.Id, b.Name }
            join c in dbContext.TableC on b.Id equals c.Id
            join d in dbContext.TableD on new { c.Id, c.Occupation } equals new { d.Id, d.Occupation }
            select new
            {
                AId = a.Id,
                BId = b.Id,
                CId = c.Id,
                DId = d.Id,
                BName = b.Name,
                DOccupation = d.Occupation,
            };

请注意,equals两侧的匿名类型中每个属性的名称,顺序和数据类型必须相同才能生效。否则它们将是两种不同的匿名类型,并且不会是等同的。