[英]Entity Framework Core Filter DbSet
Is it possible in Entity Framework Core to automatically filter a DbSet<TEntity>
of a DbContext
? 是否有可能在实体框架的核心自动筛选
DbSet<TEntity>
上DbContext
? I'm looking to implement something like that just for EntityFrameworkCore. 我正在寻找为EntityFrameworkCore实现类似的东西 。 I would like to automatically filter the
IQueryable<TEntity>
before it's beeing accessed over the DbSet<TEntity>
. 我希望在通过
DbSet<TEntity>
访问之前自动过滤IQueryable<TEntity>
DbSet<TEntity>
。
Disclaimer : I'm the owner of the project Entity Framework Plus 免责声明 :我是项目Entity Framework Plus的所有者
The EF+ Query Filter allows you to Filter the DbSet and support .NET Core (Make sure to read the limitation section) EF +查询过滤器允许您过滤DbSet并支持.NET Core(确保阅读限制部分)
Wiki: EF+ Query Filter Wiki: EF +查询过滤器
// 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: 一种选择是实现进行过滤的facade类:
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. DataContext
是您的EF DbContext,而EntityType
是您实体的类型。
Then the other classes can just use this one. 然后其他类可以使用这个。 Note I did not implement
IDisposable
here, you might want to do that. 注意我没有在这里实现
IDisposable
,你可能想要这样做。
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 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 );
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.