Reputation: 3764
I have two entities in an EF Core project: Store and Employee
Employee has a key that references Store, and also has an active flag.
When I pull back Stores from the DbContext, I want to see only those Employees that have the key that references the store in question and has an active flag.
I am stuck as to how to restrict based on the active flag.
The Minimal example looks like:
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;}
}
How can I generate the behavior I want? At the moment, this will pull back every Employee, whether active or not.
Upvotes: 1
Views: 82
Reputation: 205619
You can setup a Global Query Filter.
Simply add the following to your OnModelCreating
override:
modelBuilder.Entity<Employee>()
.HasQueryFilter(e => e.IsActive);
Unfortunately EF Core does not support query level filters. All you can do is to Disable Filters. So if you want this to be per specific query or want to query for Active == false
, I'm afraid you have to use projection as suggested in another answer.
Upvotes: 1
Reputation: 549
Something like this?
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();
}
Upvotes: 0