有些固定的条件,基本每个查询的时候需要带的条件,我们可以使用全局过滤来帮我们,这样后面的查询就不用每次都带条件了。
微软自带的:https://docs.microsoft.com/zh-cn/ef/core/querying/filters
特殊针对的过滤:https://entityframework-plus.net/query-filter
准备:
nuget Z.EntityFramework.Plus.EFCore
例子:
现在我的表中有4条数据,两条是不需要的,需要过滤这两条数据
我们过滤掉IsDeleted=1的数据
① 创建过滤配置文件 DbFilterConfiguration.cs
添加方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <summary> /// 初始化全局的过滤,如软自带的 /// </summary> /// <param name="entityType">过滤</param> /// <param name="modelBuilder">builder</param> public static void InitGobalFilter(IMutableEntityType entityType, ModelBuilder modelBuilder) { if (modelBuilder == null) { return; } IEnumerable<IMutableProperty> props = entityType.GetProperties(); if (props.Any(x => x.Name == "IsDeleted")) { ParameterExpression parameter = Expression.Parameter(entityType.ClrType, "e"); byte defaultValue = 0; BinaryExpression body = Expression.Equal( Expression.Call(typeof(EF), nameof(EF.Property), new[] { typeof(byte) }, parameter, Expression.Constant("IsDeleted")), Expression.Constant(defaultValue)); modelBuilder.Entity(entityType.ClrType).HasQueryFilter(Expression.Lambda(body, parameter)); //if (entityType.Name.ToLower().Contains("view")) //{ // modelBuilder.Query(entityType.ClrType).HasQueryFilter(Expression.Lambda(body, parameter)); //} //else //{ //modelBuilder.Entity(entityType.ClrType).HasQueryFilter(Expression.Lambda(body, parameter)); //} } }
在上下文中的OnModelCreating方法添加代码
protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); IEnumerable<Microsoft.EntityFrameworkCore.Metadata.IMutableEntityType> entityTypes = modelBuilder.Model.GetEntityTypes(); foreach (Microsoft.EntityFrameworkCore.Metadata.IMutableEntityType entityType in entityTypes) { DbFilterConfiguration.InitGobalFilter(entityType, modelBuilder); } }
这样我们每次查询的时候都会把IsDeleted=1的数据过滤
②使用Z.EntityFramework.Plus.EFCore 针对表,视图强过滤
在DbFilterConfiguration.cs中加如下代码
/// <summary> /// 正针对表进行过滤 /// </summary> /// <param name="db"></param> public static void InitContextFilter(MyDbContext db) { //根据登入人,针对某些表进行过滤 //db.Filter<ViewPFUser>(q => q.Where(x => x.IsDeleted == 0)); //db.ViewPFUser.AsNoFilter() 取消过滤 db.Filter<ViewPFUser>(q => q.Where(x => x.UserName == "admin")); }
效果:
/// <summary> /// 测试EFCore /// </summary> /// <returns></returns> [AllowAnonymous] [HttpGet("Test")] public async Task<IActionResult> Test() { //admin,admin22 List<PFUser> list2 = await _db.PFUser.AsNoTracking().ToListAsync();
//admin,admin22.admin44,admin456 取消过滤 List<PFUser> list4 = await _db.PFUser.AsNoTracking().IgnoreQueryFilters().ToListAsync(); //admin List<ViewPFUser> list3 = await _db.ViewPFUser.AsNoTracking().ToListAsync(); //admin,admin22 取消针对性的过滤 List<ViewPFUser> list5 = await _db.ViewPFUser.AsNoFilter().ToListAsync();
........
}