Oscar
Oscar

Reputation: 13970

Add filter for every query over certain entity in EF

I would like to add a filter to every query fired on my User entity to filter on IsSystemUser == false.

I had see examples using IDbCommandTreeInterceptor and IDbCommandInterceptor, and there is also a chance to override method Executing(DbCommand command, IEnumerable<DbContext> interceptionContext) on the DbContext child class, but it's unclear to me how to achieve this.

What is the easier approach to add a filter to every query fired over Users entity to filter data based on my IsSystemUser property?

Upvotes: 1

Views: 412

Answers (2)

Jonathan Magnan
Jonathan Magnan

Reputation: 11347

Disclaimer: I'm the owner of the project Entity Framework Plus

EF+ Query Filter allow you to add a filter to every queries.

// using Z.EntityFramework.Plus; // Don't forget to include this.
var ctx = new EntitiesContext();

ctx.Filter<IUser>(q => q.Where(x => !x.IsSystemUser ));

// SELECT * FROM Customers WHERE IsSystemUser = FALSE
var list = ctx.Customers.ToList();

Wiki: EF+ Query Filter

Upvotes: 1

Florian Haider
Florian Haider

Reputation: 1912

A straightforward solution would be to add a filtered IQueryable property to your DbContext, something like:

public DbSet<User> Users { get; set; }

public IQueryable<User> FilteredUsers 
{
    get
    {
        return Users.Where(u => !u.IsSystemUser);
    }
}

Upvotes: 1

Related Questions