当 child 被 ef core 标记为删除时无法获取 parent 实体

Unable to get parent Entity when child is marked deleted with ef core

我正在使用 ef core 2.0 访问 Sql 服务器数据库。这个项目有一个基本的软删除要求,所以我为所有实体定义了一个过滤器,如下所示:

protected override void OnModelCreating(ModelBuilder modelBuilder) {
    modelBuilder.Entity<Company>().HasQueryFilter(e => !e.IsDeleted);
    modelBuilder.Entity<Employee>().HasQueryFilter(e => !e.IsDeleted);
    ...
}

上面表示的类定义如下:

public partial class Employee
{
    public Guid Id { get; set; }
    public Guid CompanyId { get; set; }
    public Company Company { get; set; }
}

public partial class Company
{
    public Guid Id { get; set; }
    public ICollection<Employee> Employee { get; set; }
}

然后我尝试获取员工列表(或单个员工),如果关联公司将 IsDeleted 设置为 true,则不会检索到该员工。

查询如下:

var query = context.Employee
                   .Include(i => i.Company)
                   .Include(i => i.EmployeeType)
                   .Include(i => i.EmployeeEquipment)
                      .ThenInclude(w => w.Equipment)
                   .Where(i => i.Id == (Guid) id);
var employeeFiltered =  await query.FirstOrDefaultAsync();

因此,如果关联的公司被标记为 IsDeleted 属性 为真,则此查询不会检索到员工,这不是预期的行为。我想要的是将 Employee with Company 设置为 null。

提前致谢。

post 标题具有误导性,因为从关系的角度来看 Company 实体是 parent(a.k.a。委托人, owner, referenced) 并且 Employeechild (a.k.a. dependent, owned, referencing).

你问的仍然是可能的,但前提是关系是 optional,即依赖实体可以在没有主体实体的情况下存在。在您的情况下,它是 required 因为 FK 属性 类型不允许空值,因此要使其可选,您需要将 FK 属性 类型更改为对应的可空类型:

public partial class Employee
{
    public Guid Id { get; set; }
    public Guid? CompanyId { get; set; } // <--
    public Company Company { get; set; }
}

您可以像这样将 .IgnoreQueryFilter() 添加到查询中。

var query = context.Employee
               .IgnoreQueryFilter()
               .Include(i => i.Company)
               .Include(i => i.EmployeeType)
               .Include(i => i.EmployeeEquipment)
                  .ThenInclude(w => w.Equipment)
               .Where(i => i.Id == (Guid) id);
var employeeFiltered =  await query.FirstOrDefaultAsync();