John
John

Reputation: 644

Entity Framework 4: ObjectContext event on successful save

Is there a good way to detect when the ObjectContext changes are actually committed?

SavingChanges occurs before going to the data store but I also need a way to know if those changes where actually committed.

Thanks in advance John

Update:

What I have is a code first DbContext. This is fed into dynamic data which as I discovered uses the DbContext's internal ObjectContext (to which I have access when casting to IObjectContextAdapter). The dbcontext's SaveChanges is not called, the objectcontext's SaveChanges is used instead. All I want to do is to be notified after the save is complete (i.e. event SavedChanges) so I can invalidate my cache.

Upvotes: 5

Views: 3550

Answers (2)

Emad Alashi
Emad Alashi

Reputation: 503

pardon me, but I can't find the solution in the answer.

Let me rephrase this question according to my understanding (and my case):

I am using Dynamic Data, which ONLY accepts ObjectContext as configuration; if you use DbContext (which is the way to go with Code First) then you will have to pass the property "IObjectContextAdapater.ObjectContext" like the following:

DefaultModel.RegisterContext(() => { return ((IObjectContextAdapter) new MyDbContext()).ObjectContext; }, new ContextConfiguration() { ScaffoldAllTables = true });

The problem here is that when you save changes, the SaveChanges method of the MyDbContext is NOT called, instead Dynamic Data calls the method SaveChanges in the MyDbContext.ObjectContext. So overriding the SaveChanges in MyDbContext is useless in this case.

How can we access the SaveChanges in the ObjectContext property and change the behavior so we can write our custom code?

But anyway, the solution I found correct was in a comment by "rene" to the question above, which is adding an event handler for SavingChanges EVENT in the ObjectContext property, here is the link again:

http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.savingchanges.aspx

I hope this clears it

Upvotes: 0

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

There is no build-in event to handle this but you can override SaveChanges method in your derived context and fire any custom event specific to your own context type after you call base.SaveChanges.

Upvotes: 7

Related Questions