Home > Software design >  Linq : Select Different Object Left Join
Linq : Select Different Object Left Join

Time:12-16

I've tow contracts and one query I want to select one of them based on join result , without using where clause,

from a in pContext
     join c in vContext 
       on a.id equals c.id into av 
     from lav in av.DefaultIfEmpty()
if(lav != null )
{
   select new DTO1()
  {
   a.id,
   a.name,
   lav.description
  }
}
else
{
 select new DTO2()
 {
  a.id,
  a.name
 }
}

CodePudding user response:

EF Core translates LINQ "left join" to SQL left join and you do not need to handle nulls in this case, because it expects values from DbDataReader. Simple projection should work:

var query =
    from a in pContext
    join c in vContext on a.id equals c.id into av 
    from lav in av.DefaultIfEmpty()
    select new DTO1
    {
        a.id,
        a.name,
        lav.description
    };

CodePudding user response:

from a in pContext
     join c in vContext 
       on a.id equals c.id into av 
     from lav in av.DefaultIfEmpty()
  select new DTO()
  {
   id = a.id,
   name = a.name,
   description = lav != null ? lav.description : "No Specified"
  }

The solution is based on Svyatoslav Danyliv comment using ternary operator but with different condition to avoid the NullReferenceException.

  • Related