基于复合键的模型关系

Model relationship based on compound key

我在 EF Core 项目中有两个实体:Store 和 Employee

员工有一个引用商店的键,也有一个活动标志。

当我从 DbContext 中拉回 Stores 时,我只想看到那些拥有引用相关商店的键并具有活动标志的 Employees。

我对如何根据活动标志进行限制感到困惑。

最小示例如下所示:

public class Employee
{
      public Guid Id {get; set;}
      [ForeignKey("Store")]
      public Guid StoreId{ get; set; }
      public bool IsActive {get; set; }
}

public class Store
{
      public Guid Id {get; set;
      public List<Employee> Employees{get; set;}
}

如何生成我想要的行为?目前,这将拉回所有员工,无论是否活跃。

是这样的吗?

    using( MyDBContext db = new MyDBContext()){
        var activeEmployees = (from em in db.Employees
                              join s in db.Store on em.StoreId == s.Id
                              where em.IsActive == true
                              select em).ToList();
    }

您可以设置 Global Query Filter.

只需将以下内容添加到您的 OnModelCreating 覆盖中:

modelBuilder.Entity<Employee>()
    .HasQueryFilter(e => e.IsActive);

遗憾的是,EF Core 不支持查询级过滤器。你所能做的就是Disable Filters。因此,如果您希望这是每个特定查询或想要查询 Active == false,恐怕您必须按照另一个答案中的建议使用投影。