左边在c#中的同一个DataContext LinQ中连接两个表

时间:2015-06-09 09:41:24

标签: linq left-join

我在同一个DataContext中有两个表,如下所示。

 Table PersonnelInfo
    { 

        personnelId,
        personnelName ,          
        description,
        deathMonthYear,
        updatedBy,
        updatedAt

    }


Table PersonnelInfoOther
    { 

        personnelId,
        personnelName ,                      
        updatedBy,
        updatedAt

    }

我按如下方式定义了一个类:

  public class PersonnelInfoAll
    { 

        public short personnelId{get;set;}
        public string personnelName { get; set; }
        public string personnelNameOtherLan { get; set; }
        public string description { get; set; }
        public string deathMonthYear { get; set; }
        public int updatedBy { get; set; }
        public DateTime updatedAt { get; set; }  


    }


I need to left join first table with the second one and retrieve all the data as PersonnelInfoAll format:



public List<PersonnelInfoAllLan> GetPersonnelInfosAll()
    {
        var context = new BookDataClassesDataContext { ObjectTrackingEnabled = false };

        var personnelInfo = from u in context.PersonnelInfos
                            join b in context.PersonnelInfoOtherLans
                           on u.personnelId equals b.personnelId
                            select new PersonnelInfoAllLan
                            {
                                personnelId = u.personnelId,
                                personnelName = u.personnelName,
                                personnelNameOtherLan = b.personnelName,
                                description = u.description,
                                deathMonthYear = u.deathMonthYear,
                                updatedBy = u.updatedBy,
                                updatedAt = u.updatedAt
                            };





        return personnelInfo.ToList();
    }

这只给我一行与两者匹配。但我需要第一张表中的所有记录。有没有人可以提供帮助。

1 个答案:

答案 0 :(得分:1)

使用group join

    var personnelInfo = from p in context.PersonnelInfos
                        join l in context.PersonnelInfoOtherLans
                          on p.personnelId equals l.personnelId into g
                        from l in g.DefaultIfEmpty()
                        select new PersonnelInfoAllLan
                        {
                            personnelId = p.personnelId,
                            personnelName = p.personnelName,
                            personnelNameOtherLan = (l == null ? null : l.personnelName),
                            description = p.description,
                            deathMonthYear = p.deathMonthYear,
                            updatedBy = p.updatedBy,
                            updatedAt = p.updatedAt
                        };

如果某个人的lans不匹配,则DefaultIfEmpty()将从已加入的组返回null。这就是为什么你需要检查l的{​​{1}}。