Search code examples
c#linqasp.net-core-5.0

ASP.NET Core 5.0 Linq Outer Join


  • I've got Movements and Equipment...
    • but not all Movements have Equipment.
  • For example, a "Back Squat" requires a Barbell, Plates, etc.. but a "Pushup" doesn't require any equipment.
  • So, I've got a bridge table linking the Movements that do have Equipment.
  • I need an OUTER JOIN so I can access all of the Movements even if they do not have any Equipment.
  • ...I hope that makes sense.
  • My code below only results in Movements that have matching Equipment records in the bridge table.
Movements = (
    from mvmt   in applicationDbContext.Movements
    join mvmteq in applicationDbContext.MovementEquips on mvmt  .MvmtId  equals mvmteq.MvmtId
    join equip  in applicationDbContext.Equipment      on mvmteq.EquipId equals equip .EquipId
    orderby mvmt.MvmtId
    select new Movement
    {
        MvmtId = mvmt.MvmtId,
        MvmtDescr = mvmt.MvmtDescr
    })
    .ToList();

Solution

  •         var query =  
            from mvmt in applicationDbContext.Movements
            join mvmteq in applicationDbContext.MovementEquips on mvmt.MvmtId  
            equals mvmteq.MvmtId
            join equip  in applicationDbContext.Equipment on mvmteq.EquipId equals 
            equip.EquipId into g
            from mvmteq in g.DefaultIfEmpty()
            where mvmt.MvmtId != null
            select new
            {     
              MvmtId = mvmt.MvmtId,
              MvmtDescr = mvmt.MvmtDescr
             }).ToList();
    

    Please refer to https://learn.microsoft.com/en-gb/dotnet/csharp/linq/perform-left-outer-joins

    and

    http://msdn.microsoft.com/en-us/library/bb397895.aspx