左/右连接查询中的多个连接

时间:2013-03-13 08:20:41

标签: c# .net linq

我有一个参考表,在此表中有3个字段(IdUser1User2)。字段User2可以为空,但是当它不使用时我们使用0。

当我执行下面的Linq查询时,User2 == 0不属于结果的记录。

在这种情况下如何进行左/右连接?

class MyReference
{
    public int Id { get; set; }
    public int User1 { get; set; }
    public int User2 { get; set; }
}

class User
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

class MyClassResult
{
    public int Id { get; set; }
    public string U1FirstName { get; set; }
    public string U2FirstName { get; set; }
}

var result =
    (from myReference in context.MyReference
     join u1 in context.USER on myReference.User1 equals User.Id
     join u2 in context.USER on myReference.User2 equals User.Id
     select new MyClassResult
     {
         Id = myReference.Id,
         U1FirstName = u1.FirstName,
         U2FirstName = u2.FirstName
     }).ToList();

1 个答案:

答案 0 :(得分:3)

您必须使用into关键字和DefaultIfEmpty来获取null元素:

var result = (from myReference in context.MyReference
                join u1 in context.USER on myReference.User1 equals u1.Id
                join u2 in context.USER on myReference.User2 equals u2.Id into x2
                from un2 in x2.DefaultIfEmpty()
                select
                    new MyClassResult {
                        Id = myReference.Id, 
                        U1FirstName = u1.FirstName, 
                        U2FirstName = un2 != null ? un2.FirstName : null
                    });

作为替代方案,特别是如果myReference.User1也可以是0,您可以使用let关键字在最终选择之前获取用户信息:

var result = (from myReference in context.MyReference
            let u1 = users.FirstOrDefault(u => u.Id == myReference.User1)
            let u2 = users.FirstOrDefault(u => u.Id == myReference.User2)
            select
            new MyClassResult {
                Id = myReference.Id,
                U1FirstName = u1 != null ? u1.FirstName : null,
                U2FirstName = u2 != null ? u2.FirstName : null
            });