Alex
Alex

Reputation: 3968

Entity framework add where clause to all queries

I have a project that is using Entity framework and AspNet Identity.

One of the parameters of the IdentityUser is a deactivated field.

Within the app, if I wanted to get the users, I would do this:

var users = Context.Users //etc....

However, I do not want this query to return any deactivated users. I know I could do this

var users = Context.Users.Where(x => x.Deactivated != true);

However, I am reluctant to do this, as I am sure that in time someone will forget to add this where clause.

Is there a way for entity to do this automatically to all context queries? I have found this:

https://learn.microsoft.com/en-us/ef/core/querying/filters

But I do not have EF core and cannot upgrade to it.

I know I could make a wrapper function and call this, but I am trying to find a better solution...

Upvotes: 2

Views: 3254

Answers (2)

Ralph
Ralph

Reputation: 11

You can use Global Filters:

protected override void OnModelCreating(ModelBuilder modelBuilder){
    modelBuilder.Entity<Blog>().Property<string>("TenantId").HasField("_tenantId");
    // Configure entity filters
    modelBuilder.Entity<Blog>().HasQueryFilter(b => EF.Property<string>(b, "TenantId") == _tenantId);
    modelBuilder.Entity<Post>().HasQueryFilter(p => !p.IsDeleted);
}

Upvotes: 1

Jon Hanna
Jon Hanna

Reputation: 113322

I often use a combination of XXXStore members and XXX members where the XXXStore is the DBSet and the XXX is a query with AsNoTracking(). I then use the XXX members in queries responding to GETs and the XXXStore only when I want to update the database. E.g.

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

    public IQueryable<User> Users => UserStore.AsNoTracking();

This gives the advantage of not tracking entities that won't be updated, but with a DRY approach that means not adding the AsNoTracking() verbosely all over the place.

This approach can easily be combined with a where clause:

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

    public IQueryable<User> Users => UserStore.AsNoTracking().Where(u => !u.Deactivated);

Filters can also work, but an advantage to this approach is that it's easy to make an exception when you really do need to access a deactivated user, too.

Upvotes: 6

Related Questions