1 year ago

#132300

test-img

mankers

Soft delete does not work for queries using OR

I have used "Soft Delete" pattern implemented at EF TechEd session (code available here: https://github.com/rowanmiller/Demo-TechEd2014). The solution worked well until I tried to execute query with condition including OR:

dbSet.Where(x => x.Name == "Foo" || x. Name == "Bar");

This produced SQL query like below:

SELECT `Extent1`.`Id`, `Extent1`.`Name`
FROM `Table` AS `Extent1`
WHERE ('Foo' = `Extent1`.`Name`) OR ('Bar' = `Extent1`.`Name`) AND `Extent1`.`Deleted` != 1;

As you can see, Deleted flag checking is added in the end of WHERE clause, but the order of conditions causes that deleted entries are also returned.

I suspect that there is a problem with implementation of SoftDeleteQueryVisitor.

Link: https://github.com/rowanmiller/Demo-TechEd2014/blob/master/FakeEstate.ListingManager/Models/EFHelpers/SoftDeleteQueryVisitor.cs

public class SoftDeleteQueryVisitor : DefaultExpressionVisitor
{
    public override DbExpression Visit(DbScanExpression expression)
    {
        var column = SoftDeleteAttribute.GetSoftDeleteColumnName(expression.Target.ElementType);
        if (column != null)
        {
            var table = (EntityType)expression.Target.ElementType;
            if (table.Properties.Any(p => p.Name == column))
            {
                var binding = DbExpressionBuilder.Bind(expression);
                return DbExpressionBuilder.Filter(
                    binding,
                    DbExpressionBuilder.NotEqual(
                        DbExpressionBuilder.Property(
                            DbExpressionBuilder.Variable(binding.VariableType, binding.VariableName),
                            column),
                        DbExpression.FromBoolean(true)));
            }
        }

        return base.Visit(expression);
    }
}

c#

entity-framework

interceptor

soft-delete

0 Answers

Your Answer

Accepted video resources