Entity Framework question to do with timing of save
I have an object that has an ObjectContext. OnSave of that object I am running an action using that ObjectContext like this:
public void SaveChangesAction(ObjectContext context)
{
// Validate the state of each entity in the context
// before SaveChanges can succeed.
foreach (ObjectStateEntry entry in
context.ObjectStateManager.GetObjectStateEntries(
EntityState.Added | EntityState.Modified))
{
var type = entry.Entity.GetType();
var RepoBase = typeof(RepositoryBase<myEntityFrameworkObject>);
MethodInfo mi = RepoBase.GetMethod("GenerateLog");
MethodInfo constructed = mi.MakeGenericMethod(type);
constructed.Invoke(this, new object[] { entry.Entity });
}
}
Inside my "GenerateLog" method I am taking my Entity and Detaching it from the ObjectContext (so that it can be turned into a Binary Object without going through all the Lazy Loaded objects as well).
After turning into a Binary Object, I create another object (of a different Type) that holds the Binary data. I call this.ObjectContext.AddObject('TableName', myNewObject);
.
Then I call this on my object I previously detached (entityState is the previous State of the Entity):
if (entity.EntityState != entityState)
{
this.ObjectContext.AddObject(entity.GetType().Name, entity开发者_StackOverflow社区);
}
At this point, the code goes back to the SaveChangesAction method from above. Neither of those objects are in my ObjectContext now and therefore neither of them saves to my database.
I understand that I am already doing something bad by modifying objects inside a ForEach that affects them, but I have no idea how else to do this considering this is code I need to run right before my ObjectContext is saved.Few points:
- That reflection smells. You know what repositories you have so simply make dictionary of with type as lookup value.
- I wonder how is it possible that your code even run. If you detach the entity inside the loop it should modify iterated collection and throw an exception. This can be avoided by calling
ToArray
orToList
in your state manager query. - You are iterating added and modified entities and detaching them but after that you always add entity as new so instead of updating the old entity you are trying to insert a duplicate
- Detaching object will break all relations. I'm almost sure that some changes in relations will be lost by this action and adding or attaching object back to context will not recreate them.
- The method takes
ObjectContext
as parameter but your other code snippets are usingthis.ObjectContext
so it is absolutely not clear how these parts relate to themselves - There is not
context.SaveChanges
so if you don't call it elsewhere it is the reason why no changes are saved
精彩评论