简体   繁体   中英

How to set filter option on DbSet property in Entity Framework?

I have a DbSet property in my context class as follows:

public class ProjectContext: DbContext
{
    public ProjectContext(): base("name=DBCS")
    {
    }

    public DbSet<Employee> EmployeeDbSet { get; set; }
}

This property is being used in many places of my project. Now I need to set a generic condition on Employee such as I need only active employees. I can get active employees by simply filtering my linq queries like this:

var employees = context.EmployeeDbSet.where(e => e.IsActive).ToList();

Since I've already written many queries in many places of my project, now I have to rewrite them all which is very difficult, time-consuming and error prone.

As this is a generic condition and I want to set this on all queries, I'm looking for a way to set the condition on EmployeeDbSet property instead.

Can it be accomplished?

You can add a IQueryable<Employee> property to your DbContext that returns the active where condition set.

Example;

public IQueryable<Employee> ActiveEmployees 
{
    get
    {
        return EmployeeDbSet.Where(e => e.IsActive);
    }
}

This way you can combine it with other where conditions by just doing;

context.ActiveEmployees.Where(x=> x.name == "john");

After you do this you cant use methods that declared directly in DbSet<T> . To use find method after you use where, You can add a new find method yourself as follows;

public static class DbModelExtensions
{
    public static Employee Find(this IQueryable<Employee> query, int id)
    {
        return query.Where(x => x.Id == id).FirstOrDefault();
    }
}

This adds a extension method Find to only IQueryable<Employee> if its namespace is referenced in current file.

Then you can use it like this;

context.ActiveEmployees.Find(15);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM