Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 209
Thomas Gassmann Avatar asked Dec 14 '22 00:12

Thomas Gassmann


2 Answers

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 );
    }
}
like image 182
İrfan Sağır Avatar answered Dec 17 '22 02:12

İrfan Sağır


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();
like image 39
Jonathan Magnan Avatar answered Dec 17 '22 01:12

Jonathan Magnan