如何在Fluent LINQ中加入or子句

时间:2014-04-04 16:57:18

标签: c# linq

我想加入两张桌子。

TSQL将是:

SELECT * 
FROM User u INNER JOIN Hierarchy h ON u.OrganisationId = h.OrganisationId 
   OR u.OrganisationId = h.OwnerOrganisationId

我已经搜索过,没有人能够流利地回答这个问题。我能想到的最接近的是:

var join1 = context.User.Join(context.Hierarchy, u => u.OrganisationId, h => h.OrganisationId, uh => new {u, h});
var join2 = context.User.Join(context.Hierarchy, u => u.OrganisationId, h => h.OwnerOrganisationId, uh => new {u, h});
var desiredResult = join1.Union(join2);

但这似乎非常低效。

1 个答案:

答案 0 :(得分:2)

流利语法

var orJoin = context.User.SelectMany(
                u => context.Hierarchy.Where(h => u.OrganisationId == h.OrganisationId || u.OrganisationId == h.OwnerOrganisationId),
                (u, h) => new { u, h }
             );

查询语法

var orJoin = from u in context.User
             from h in context.Hierarchy
             where u.OrganisationId == h.OrganisationId || u.OrganisationId == h.OwnerOrganisationId
             select new { u, h };