即使child为null,Linq也会联接返回父级

时间:2017-03-10 02:50:27

标签: c# linq dynamics-crm-2015

我想选择fake2为null的所有行以及所有在fake2上都有连接的行 下面的代码没问题,但我想在选择linq查询中完成所有操作以提高效率。

var rows = (
            from a in crmLinqContext.fakeSet
            join b in crmLinqContext.fake2Set on a.fake2.Id equals b.Id
            join c in crmLinqContext.fake3Set on b.field equals c.field
            where c.anotherField == "THIS_BIT_OF_TEXT"
            select a);

List<myObject> objects = new List<myObject>();
foreach(var row in rows)
{
    objects.Add(row);
}
 rows = (
    from a in crmLinqContext.fakeSet
    where s.fake2 == null
    select a);

foreach (var row in rows)
{
    objects.Add(row);
}
return objects;

2 个答案:

答案 0 :(得分:1)

在linq中使用左连接,如下所示,它没有经过测试,但它的作用是它留下了外部连接fakeSet和fakeSet2。

var rows =
    from a in crmLinqContext.fakeSet
    join b in crmLinqContext.fake2Set on a.fake2.Id equals b.Id into subset
    from b in subset.DefaultIfEmpty()
    join c in crmLinqContext.fake3Set on b.field equals c.field
    where c.anotherField == "THIS_BIT_OF_TEXT"
    select a;

答案 1 :(得分:0)

var rows = (
            from a in crmLinqContext.fakeSet
            join b in crmLinqContext.fake2Set on a.Id equals b.Id
            join c in crmLinqContext.fake3Set on b.field equals c.field
            where c.anotherField == "THIS_BIT_OF_TEXT"
            select a)
            .Concat(
            from a1 in crmLinqContext.fakeSet
            where a1.fake2 == null
            select a1);