Entity Framework 4: ObjectContext event on successful save

有些话、适合烂在心里 提交于 2019-12-22 06:00:00

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/8688170/entity-framework-4-objectcontext-event-on-successful-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!