Search code examples
c#entity-frameworkormforeign-keys.net-7.0

How can I filter an optional model inside include in Entity Framework Core


I'm using .NET 7 and i have the following model class:

public class MachineSchedule
{
   public int MachineScheduleId { get; set; }
   public string Name

   #region Relationships

   public virtual ICollection<Shift>? Shifts { get; set; }

   #endregion
}

I want to make a query filtering, for example, the "Shift" model class, so I have:

machineScheduleDto = _context
         .AsNoTracking()
         .Include(m => m.Shifts.Where(s => s.Type == 1));

But since my relationship is optional, I receive the following warning:

Possible null reference argument for parameter.

How can I made the query properly without receive any error or warning? I know that if I add "required" in the declaration of the class, all of the problems are solved, but my relationship is really optional, so add this seems wrong to me.


Solution

  • You can use the null-forgiving operator (!):

    machineScheduleDto = _context
         .AsNoTracking()
         .Include(m => m.Shifts!.Where(s => s.Type == shiftType));
    

    ...and I wonder if it will go faster the code:

    machineScheduleDto = _context.Shifts!
         .AsNoTracking()
         .Where(s => s.Type == shiftType)
         .Include(c => c.MachineSchedule)
         .Select(c => c.MachineSchedule);