Linq外连接可能的问题

时间:2012-05-07 22:47:00

标签: c# linq tdd

        var query1 = from l in context.Logs
                    where l.LogID == maxid
                    select l;
        int count1 = query1.Count();

        var query2 = from ld in context.LogDetails
                     where ld.LogID == maxid
                     select ld;
        int count2 = query2.Count();

        Assert.AreEqual(1,count1);
        Assert.AreEqual(0,count2);

我希望我能以更好的方式编写上述查询。如果我使用TSQL,我可以使用OUTER JOIN并过滤以查看ld.LogID是否为null。但我不知道如何在LINQ中这样做。有什么方法可以清理它吗?

感谢您提供帮助。

2 个答案:

答案 0 :(得分:3)

Outer joins are possible in LINQ

var query = from log in context.Logs
            join logDetail in context.LogDetails
                on log.LogID = logDetail.LogID into lj
            from item in lj.DefaultIfEmpty()
            select new { log.LogID, MissingDetails = lj == null };

答案 1 :(得分:0)

这是使用导航属性的外部联接:

from log in context.Logs
from logDetail in log.LogDetails.DefaultIfEmpty()
select new {log, logDetail}

不要忘记将logdetail测试为null。