Reliable way to run code against Entities just Inserted with ObjectContext?
I have some code that needs to run every time an Entity is Inserted into my database, th开发者_开发问答e problem is that this code requires the Entity PrimaryKey.
I have found that I can get the Entities from the ObjectStateManager with EntityState.Unchanged and that is my object after Insert, but I am not sure if that will always be the only objects with "Unchanged" as their EntityState in the ObjectContext.Is there a reliable way to run code only against objects that have JUST been Inserted with ObjectContext?
Yes there is a way. You must call overloaded SaveChanges
which will not accept changes after saving automatically and instead you will be responsible for calling AcceptAllChanges
. In this scenario objects will be still in Added state after calling SaveChanges
(but only till you call AcceptAllChanges
). The general code should look like:
using (var scope = new TransactionScope(...))
{
context.SaveChanges(SaveOptions.DetectChangesBeforeSave);
// Run your code here
context.AcceptAllChanges();
scope.Complete();
}
Transaction scope is not necessary - it is just example of the approach if you post insert code must run in the transaction with insertion.
You can also wrap that code into overriden SaveChanges
so you will have it in centralized place.
精彩评论