Search code examples
c#.netlinqlinq-to-entities

Optional condition in join clause - Linq


I have below linq query

 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

     };

In above query when ad.AddressTypeID is null, it is not returning any result.

I have requirement if ad.AddressTypeID is null,than from LuAddressTypes fetch default record where AddressTypeCd=1. If I try this way

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

     });

in result v2.AddressName always returning null. I am unable to specify AddressTypeCd=1 where condition as well. AddressTypeCd=1 is not ad.AddressTypeID.

I need v2.AddressName where AddressTypeCd=1. How can I do that? Find related entities all related entities


Solution

  • You can't use the standard LINQ join, but in LINQ to Entities you could use the alternative join syntax based on correlated Where - EF is smart enough to translate it to JOIN.

    In your case, instead of

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

    you could use

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

    which is translated to something like this

    INNER JOIN [dbo].[LuAddressTypes] AS [Extent3]
        ON ([Extent2].[AddressTypeID] = [Extent3].[AddressTypeID])
            OR (([Extent2].[AddressTypeID] IS NULL) AND (1 = [Extent3].[AddressTypeCd]))
    

    If you want LEFT OUTER JOIN, simply add .DefaultIfEmpty() at the end of the above line.