简体   繁体   中英

Ignoring an expression visitor or IDbCommandTreeInterceptor

For our database, which requires soft deletes, we have an IsActive bit column. When false, it indicates the record has been marked deleted.

For 99% of the time, queries should only include records that have IsActive set to true. In Entity Framework 6, we're using a custom DefaultExpressionVisitor (via an IDbCommandTreeInterceptor ) to automatically make this check when the column exists on a table.

However, on very rare occasions, this behavior needs to be overridden. Is there a way to write an extension method for IQueryable or a setting on the DbContext that the expression visitor or command tree interceptor could check for?

I'm hoping to do something like

var query = queryable.IncludeInactive().Where(...);

or

_dbContext.IncludeInactive = true;
var query = queryable.Where(...);
_dbContext.IncludeInactive = false;

to affect the behavior described above that would otherwise occur when doing this:

var query = queryable.Where(...);

I would prefer the extension method route if possible.

You could try to put an IsActive property ON your custom DefaultExpressionVisitor, and change it to don't do its magic when it's set to false, and also keep a reference of that DefaultExpressionVisitor into a singleton (this singleton would be following the same pattern as the static property of Transaction.Current, you just have to keep that singleton somewhere, but a different one per thread).

Create another class (the "IncludeInactive" class) that follows the same pattern as a TransactionScope (it just has to implement IDisposable), but on its constructor its sets the singleton IsActive property to false and on its Dispose method, set it to true.

Then you would use it like this:

using(var inactive = new IncludeInactive())
{
    var query = queryable.Where(...);
}

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