如何在 Entity Framework Core 中筛选包含中的可选模型

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

提问人:guirms 提问时间:10/12/2023 最后编辑:marc_sguirms 更新时间:10/12/2023 访问量:48

问:

我正在使用 .NET 7,我有以下模型类:

public class MachineSchedule : BaseModel
    {
        public int MachineScheduleId { get; set; }
        public EWeekDay WeekDay { get; set; }
        public TimeSpan InitialProductionTime { get; set; }
        public TimeSpan FinalProductionTime { get; set; }
        public DateTime? UpdatedAt { get; set; }

        #region Relationships

        public virtual ICollection<MachineOperation>? MachineOperations { get; set; }
        public virtual ICollection<Shift>? Shifts { get; set; }
        public virtual ICollection<ScheduledStop>? ScheduledStops { get; set; }

        #endregion
    }

我想进行查询过滤,例如“Shift”模型类,所以我有:

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

但是,由于我的关系是可选的,因此我收到以下警告:

参数的可能 null 引用参数。

我该如何解决这个问题?我知道如果我在类的声明中添加“required”,所有问题都解决了,但我的关系确实是可选的,所以添加这个对我来说似乎是错误的。

C# 实体框架 ORM 外键 net-7.0

评论


答:

2赞 Fabio Caruso 10/12/2023 #1

您可以使用容错 null 运算符 (!):

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

...我想知道它是否会加快代码:

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