简体   繁体   中英

Entity Framework Core Filter DbSet

Is it possible in Entity Framework Core to automatically filter a DbSet<TEntity> of a DbContext ? I'm looking to implement something like that just for EntityFrameworkCore. I would like to automatically filter the IQueryable<TEntity> before it's beeing accessed over the DbSet<TEntity> .

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

The EF+ Query Filter allows you to Filter the DbSet and support .NET Core (Make sure to read the limitation section)

Wiki: EF+ Query Filter

// 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();

One option would be to implement a facade class that does the filtering:

public class DataService
{
    private readonly DataContext _context;

    public DataService(DataContext context)
    {
        _context = context;
    }

    public IQueryable<EntityType> EntityTypes => _context.EntityTypes.Where(t => t.Something == true);
}

Where DataContext is your EF DbContext, and EntityType is the type of your entity.

Then the other classes can just use this one. Note I did not implement IDisposable here, you might want to do that.

you can look at the link below.

https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-2.0#model-level-query-filters

Example

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    public int TenantId { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>().HasQueryFilter(
            p => !p.IsDeleted
            && p.TenantId == this.TenantId );
    }
}

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