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>
.
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 );
}
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With