简体   繁体   中英

EF Core SetQueryFilter Reverse IsActive to IsDeleted in OnModelCreating

I was using IsActive column in my all tables. When its false nothing return I applied filter in OnModelCreating.

But I changed it to IsDeleted column so when IsDeleted is true nothing will return from DB.

Here is my code snippet for filter. But the problem is when IsDeleted is true I'm getting my data from DB. But I want to when IsDeleted is false I'll get data from DB.

var isDeletedProperty = entityType.FindProperty("IsDeleted");
if (isDeletedProperty != null && isDeletedProperty.ClrType == typeof(bool))
{
    var parameter = Expression.Parameter(entityType.ClrType, "p");
    var filter = Expression.Lambda(Expression.Property(parameter, isDeletedProperty.PropertyInfo), parameter);
    entityType.SetQueryFilter(filter);
}
var isDeletedProperty = entityType.FindProperty("IsDeleted");
if (isDeletedProperty != null && isDeletedProperty.ClrType == typeof(bool))
{
    var parameter = Expression.Parameter(entityType.ClrType, "p");
    var filter = Expression.Lambda(
        Expression.Equal(
            Expression.Property(parameter, isDeletedProperty.PropertyInfo),
            Expression.Constant(false, typeof(bool))
        )
        , parameter);
    entityType.SetQueryFilter(filter);
}

Currently your filter is like this

p => p.IsDeleted

ie returns deleted entities. While what you really need is

p => !p.IsDeleted

The Expression equivalent of C# ! operator is Expression.Not , so simply surround the current condition with it:

var body = Expression.Not(Expression.Property(parameter, isDeletedProperty.PropertyInfo));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM