Sto usando un IDbCommandTreeInterceptor
per abilitare le eliminazioni IDbCommandTreeInterceptor
sul mio modello.
System.Data.Entity.Infrastructure.Interception.DbInterception.Add(
new SoftDeleteInterception());
Voglio essere in grado di disabilitare temporaneamente l'intercettore in modo da poter selezionare un'entità "cancellata" ai fini del controllo.
Tuttavia, sembra che la raccolta DbInterception
sia a livello di assembly.
C'è un modo per creare un nuovo DbContext
senza intercettazione? O anche un modo per aggiungere l'intercettore a DbContext
ogni volta che viene creato?
Ho esteso la mia classe di contesto db con proprietà aggiuntive
[DbConfigurationType(typeof(DbConfig))]
public partial class YourEntitiesDB
{
public bool IgnoreSoftDelete { get; set; }
}
Quindi nel metodo TreeCreated (...) controllo questo flag e se è vero allora non va oltre al QueryVisitor
public class SoftDeleteInterceptor : IDbCommandTreeInterceptor
{
public SoftDeleteInterceptor()
{
}
public void TreeCreated(DbCommandTreeInterceptionContext interceptionContext)
{
var db = interceptionContext.DbContexts.FirstOrDefault() as YourEntitiesDB;
if (db!=null && db.IgnoreSoftDelete)
{
// Ignore soft delete interseptor (Used in archives)
return;
}
if (interceptionContext.OriginalResult.DataSpace == DataSpace.CSpace)
{
var queryCommand = interceptionContext.Result as DbQueryCommandTree;
if (queryCommand != null)
{
var newQuery = queryCommand.Query.Accept(new SoftDeleteQueryVisitor());
interceptionContext.Result = new DbQueryCommandTree(
queryCommand.MetadataWorkspace,
queryCommand.DataSpace,
newQuery);
}
var deleteCommand = interceptionContext.OriginalResult as DbDeleteCommandTree;
if (deleteCommand != null)
{
var column = SoftDeleteAttribute.GetSoftDeleteColumnName(deleteCommand.Target.VariableType.EdmType);
if (column != null)
{
var setClauses = new List<DbModificationClause>();
var table = (EntityType)deleteCommand.Target.VariableType.EdmType;
if (table.Properties.Any(p => p.Name == column))
{
setClauses.Add(DbExpressionBuilder.SetClause(
DbExpressionBuilder.Property(
DbExpressionBuilder.Variable(deleteCommand.Target.VariableType, deleteCommand.Target.VariableName),
column),
DbExpression.FromBoolean(true)));
}
var update = new DbUpdateCommandTree(
deleteCommand.MetadataWorkspace,
deleteCommand.DataSpace,
deleteCommand.Target,
deleteCommand.Predicate,
setClauses.AsReadOnly(),
null);
interceptionContext.Result = update;
}
}
}
}
}
Per usarlo, ho appena impostato il flag su true quando necessario
YuorEntitiesDB DB = new YuorEntitiesDB();
DB.IgnoreSoftDelete = true;
DB.Records.Where(...)