简体   繁体   中英

EF Core HasQueryFilter on Include()

I'm a bit confused if the HasQueryFilter method should work on entities that are joined by the Include() method.

From this (old) article, they state the following: https://blogs.msdn.microsoft.com/dotnet/2017/05/12/announcing-ef-core-2-0-preview-1/

Filters are applied automatically when queries retrieve data of specific types directly as well as through navigation properties, eg using the Include() method.

What I have in my DbContext class is the following:

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<Post>().HasQueryFilter(x => x.Removed == null);
}

If I then execute the following, then it also retrieves all the Posts records where Removed is not null.

// Doesn't apply the query filter because of the Include()
var blog = _dbContext.Blogs.Include(x => x.Posts).Where(x => x.Id == 100);

If I query Post directly, then the HasQuerFilter does its job.

// Here query filter works, because of query directly on Entity
var posts = _dbContext.Posts.ToList();

So is it correct that this functionality doesn't work (yet?) on entities that are joined using Include() ? Or am I mising something?

This is an issue with tracking (which is why multiple using statements works).

There are different ways to do it though:

See How do I clear tracked entities in entity framework

We used: _dbContext.Entry(blog).State = EntityState.Detached;

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