EF Core SetQueryFilter Reverse IsActive to IsDeleted in OnModelCreating

Viewed 412

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);
}
2 Answers

Currently your filter is like this

p => p.IsDeleted

i.e. 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));
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);
}
Related