简体   繁体   中英

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://docs.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...

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 GET s and the XXXStore only when I want to update the database. Eg

    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.

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);
}

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