Reputation: 655
I'm using ef core 2.0 to access a Sql Server database. This project has a basic soft delete requirement, so i i've defined a filter for all Entities like this:
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.Entity<Company>().HasQueryFilter(e => !e.IsDeleted);
modelBuilder.Entity<Employee>().HasQueryFilter(e => !e.IsDeleted);
...
}
The classes represented above were defined as following:
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; }
}
Then i'm trying to get a list of employees (or a single employee) and if the associated company has IsDeleted set to true, the employee is not retrieved.
The query is the following:
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();
So this query don't retrieved the employee if the Company associated is marked with IsDeleted property to true which is not the expected behaviour. What i would like is to get the Employee with Company set to null.
Thanks in advance.
Upvotes: 1
Views: 601
Reputation: 470
You can just add .IgnoreQueryFilter()
to the query like this.
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();
Upvotes: 1
Reputation: 205569
The post title is misleading, because from relational standpoint Company
entity is the parent (a.k.a. principal, owner, referenced) and Employee
is the child (a.k.a. dependent, owned, referencing).
Still what you are asking is possible, but only if the relationship is optional, i.e. the dependent entity could exist without principal entity. In your case it's required because the FK property type does not allow null value, so to make it optional, you need to change the FK property type to the corresponding nullable type:
public partial class Employee
{
public Guid Id { get; set; }
public Guid? CompanyId { get; set; } // <--
public Company Company { get; set; }
}
Upvotes: 2