I need to update incoming data from database before they are send into application. I'm using DbCommandInterceptor when I can override ReaderExecuted method for this. Here I can change incoming data. This works well for properties directly in entity.
Here is an example:
public override void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
var dbContext = interceptionContext.DbContexts.FirstOrDefault();
if (dbContext != null)
{
var entities = dbContext.ChangeTracker.Entries().Where(p => p.State == EntityState.Unchanged);
foreach (var entity in entities)
{
if (entity.Entity.GetType().BaseType == typeof(T01_Object))
{
entity.Property("ObjectName").CurrentValue = "test name";
entity.Property("ObjectName").OriginalValue = "test name";
}
}
}
base.ReaderExecuted(command, interceptionContext);
}
This works, changed data are propagated into application.
But now I need to change data in nested collection. Entity T01_Object has property T102_Child which is collection of T102_Child
I've tried this:
public override void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
var dbContext = interceptionContext.DbContexts.FirstOrDefault();
if (dbContext != null)
{
var entities = dbContext.ChangeTracker.Entries().Where(p => p.State == EntityState.Unchanged);
foreach (var entity in entities)
{
var typeAttributesRawCollection = entity.Collection("T102_Child");
if (typeAttributesRawCollection != null)
{
foreach (var t102Entity in (IEnumerable)typeAttributesRawCollection.CurrentValue)
{
var test = (T102_Child)t102Entity;
test.ChildName = "Test name";
}
}
}
}
base.ReaderExecuted(command, interceptionContext);
}
But in this case I can not see modify data in application. There are original values. How to solve this problem. Should I call some method to let to entity framework know the data are changed? This is only one way modification without saving into database.
The entity type is some background logic (data encryption/decryption) and entity T102_Child is used in many places of the application. So I need have this logic in one place in application. The given example is only a simplification of the problem.
I tried writing a demo and it works as expected. Does this help?
Please note that any
SaveChanges()will persist the overwritten values, which is not what you want, I assume.