连接子句中的可选条件-Linq

时间:2018-11-22 10:09:44

标签: c# .net linq linq-to-entities

我在下面的linq查询中

 var resultGuardian = from s in _db.Students
     join sg in _db.StudentGuardians on s.StudentID equals sg.StudentID
     join g in _db.Guardians on sg.GuardianId equals g.GuardianId
     join lr in _db.luRelationTypes on sg.RelationTypeID equals lr.RelationTypeID
     join ga in _db.GuardianAddresses on g.GuardianId equals ga.GuardianId
     join ad in _db.Addresses on ga.AddressID equals ad.AddressID
     join lt in _db.luAddressTypes on ad.AddressTypeID equals lt.AddressTypeID
     join lg in _db.luGenders on g.GenderID equals (int?)lg.GenderID into ssts
     from gdnr in ssts.DefaultIfEmpty()
     where
         s.TenantID == tenantid && sg.TenantID == tenantid && g.TenantID == tenantid &&
         s.StatusId == (int?)Extension.StatusType.Active //1
         && g.StatusID == (int?)Extension.StatusType.Active &&
         lr.StatusID == (int?)Extension.StatusType.Active && lr.TenantID == tenantid &&
         s.StudentID == sid
     select new
     {
         g.FirstName,
         g.LastName,
         IsPrimary = sg.IsPrimaryGuardian,
         g.Education,
         g.Email,
         g.Phone,
         lr.RelationCD,
         ga.IsStudentAddress,
         gdnr.GenderCD,
         lt.AddressName,
         ad.Address1,
         ad.Address2,
         ad.City,
         ad.State,
         ad.Zipcode

     };

在上面的查询中,当ad.AddressTypeIDnull时,它不返回任何结果。

我要求ad.AddressTypeIDnull,而不是LuAddressTypesAddressTypeCd=1获取默认记录。如果我这样尝试

join lt in LuAddressTypes on ad.AddressTypeID equals lt.AddressTypeID into v1
from v2 in v1.DefaultIfEmpty()
select new
     {      
         v2.AddressName,
         g.Phone,..

     });

结果 v2.AddressName 始终返回null。我也无法指定AddressTypeCd=1 where条件。 AddressTypeCd=1不是ad.AddressTypeID

我需要v2.AddressName,其中AddressTypeCd=1。我怎样才能做到这一点? 查找相关实体all related entities

1 个答案:

答案 0 :(得分:4)

您不能使用标准的LINQ join,但是在LINQ to Entities中,您可以使用基于相关Where的替代联接语法-EF足够聪明,可以将其转换为{{1} }。

以您的情况代替

JOIN

您可以使用

join lt in _db.luAddressTypes on ad.AddressTypeID equals lt.AddressTypeID

翻译成这样的东西

from lt in _db.luAddressTypes.Where(lt => ad.AddressTypeID == lt.AddressTypeID
    || (ad.AddressTypeID == null && lt.AddressTypeCd == 1))

如果要INNER JOIN [dbo].[LuAddressTypes] AS [Extent3] ON ([Extent2].[AddressTypeID] = [Extent3].[AddressTypeID]) OR (([Extent2].[AddressTypeID] IS NULL) AND (1 = [Extent3].[AddressTypeCd])) ,只需在上一行的末尾添加LEFT OUTER JOIN