我在下面的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.AddressTypeID
为null
时,它不返回任何结果。
我要求ad.AddressTypeID
是null
,而不是LuAddressTypes
从AddressTypeCd=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
答案 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
。