JaSHin
JaSHin

Reputation: 277

Adding where condition to all requests of entity framework core

I have same problem as in following

Adding Where Condition to All Requests EF6

but I use Entity Framework core. Is it possible to do the same?

Upvotes: 2

Views: 1612

Answers (2)

Saeb Amini
Saeb Amini

Reputation: 24429

The answer is YES since EF Core >= 2.0 with Global Query Filters :)

Assuming the below entity:

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public bool IsDeleted { get; set; }
}

You can configure a global query filter in OnModelCreating using HasQueryFilter:

modelBuilder.Entity<Post>().HasQueryFilter(p => !p.IsDeleted);

With the above, Posts that have IsDeleted set to true no longer will be included in the results, unless you explicitly have a Where clause for them, or disable global filters in that query:

var posts = db.Posts
    .IgnoreQueryFilters()
    .ToList();

Some common applications of this feature are:

Soft delete - An Entity Type defines an IsDeleted property.

Multi-tenancy - An Entity Type defines a TenantId property.

Upvotes: 2

Jonathan Magnan
Jonathan Magnan

Reputation: 11347

The answer is NO

But it may be possible in the future.

Entity Framework Core doesn't have yet Interceptor which is required to built this kind of feature.

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

That is probably the closest you can do at this moment.

The context is filtered but not related entities in Include method (require Interceptor).

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

ctx.Filter<Post>(q => q.Where(x => !x.IsSoftDeleted));

// SELECT * FROM Post WHERE IsSoftDeleted = false
var list = ctx.Posts.ToList();

Wiki: Query Filter

Upvotes: 2

Related Questions