4

我有一个参考表,在这个表中有 3 个字段(Id, User1, User2)。该字段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();
4

1 回答 1

3

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

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
            });
于 2013-03-13T09:00:16.030 回答