Thomas Gassmann
Thomas Gassmann

Reputation: 781

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>.

Upvotes: 10

Views: 15476

Answers (3)

İrfan Sağır
İrfan Sağır

Reputation: 134

you can look at the link below.

https://learn.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 );
    }
}

Upvotes: 10

Jonathan Magnan
Jonathan Magnan

Reputation: 11327

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

Upvotes: 4

juunas
juunas

Reputation: 58723

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.

Upvotes: 3

Related Questions