1、设置一个基类(BaseEntity),包含IsDeleted属性
public class BaseEntity { [Key, DatabaseGenerated(DatabaseGeneratedOption.None)] public long Id { get; set; } = YitIdHelper.NextId(); public bool IsDeleted { get; set; } = false; }
2、所有用到软删除的类继承于此类,然后在MyDbContext中的OnModelCreating方法中实现全局过滤
protected override void OnModelCreating(ModelBuilder mb) { //全局过滤 foreach (var entityType in mb.Model.GetEntityTypes() .Where(e => typeof(BaseEntity).IsAssignableFrom(e.ClrType))) { mb.Entity(entityType.ClrType).Property<bool>(nameof(BaseEntity.IsDeleted));//也可以直接填写 "IsDeleted" var parameter = Expression.Parameter(entityType.ClrType, "e"); var body = Expression.Equal( Expression.Call(typeof(EF), nameof(EF.Property), new[] { typeof(bool) }, parameter, Expression.Constant(nameof(BaseEntity.IsDeleted))), Expression.Constant(false)); mb.Entity(entityType.ClrType).HasQueryFilter(Expression.Lambda(body, parameter)); } }
3、使用,无需做任何处理,和平常一样写语句就可以;如果需要查询所有包含软删除掉的数据,需要使用 IgnoreQueryFilters()
执行次查询语句,只会查询出isdeleted为0的数据
var list = await _mathDb.UserGradesAuthorization.Where(x => x.UserAccount == Account).Select(x => new GetGradeInfoProfile { GradeCode = x.MathGradesId, GradeName = x.MathGrades.GradeName }).OrderBy(x => x.GradeCode).ToListAsync();
忽略过滤查询所有数据使用 IgnoreQueryFilters()
var list = await _mathDb.UserGradesAuthorization.IgnoreQueryFilters().Where(x => x.UserAccount == Account).Select(x => new GetGradeInfoProfile { GradeCode = x.MathGradesId, GradeName = x.MathGrades.GradeName }).OrderBy(x => x.GradeCode).ToListAsync();
标签:CORE,ClrType,EF,查询,BaseEntity,var,NET6,Expression,IsDeleted From: https://www.cnblogs.com/Swaggy-yyq/p/16805494.html