开发者

How to hook an action after SaveChanges is successful

Our product has to be interfaced with multiple client/partner systems. For example, when a person is added/updated we have to notify changes to a 3rd-party system, for example by calling a web service or creating a xml file in a folder, etc.

We need a "hook" after SaveChanges has successfully persisted changes in the database.

Lots of information can be found about how to execute business logic when saving changes (before changes are persisted in the database), but less about executing logic after changes are persisted.

After investig开发者_如何学Goating, I think to use the following:

// Persist data
cxt.SaveChanges(false);
// TODO: execute business logic that can get data changes
// Discard changes and set entities as unmodified
ctx.AcceptAllChanges();

Does anyone have a better solution for this scenario?


I know this question is a bit old, but figure that I would add this for anyone else searching on this topic.

I would recommend checking out EFHooks. The official version is a bit stale (e.g. .NET 4 only), but I have forked the project and published a new NuGet package, VisoftInc.EFHooks.

You can read more about both packages in this post: http://blogs.visoftinc.com/2013/05/27/hooking-into-ef-with-efhooks/

Basically, EFHooks will let you hook into EF (e.g. PostInsert or PostUpdate) and run some code. The hooks are Pre/Post for Insert/Update/Delete.

One thing to note is that this is based on the DbContext, so if you are still using the ObjectContext for EF, this solution won't work for you.


You can override savechanges, then do the updating of the 3rd party systems at the same time as you save the data to the database.

see: http://thedatafarm.com/blog/data-access/objectcontext-savechanges-is-now-virtual-overridable-in-ef4/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜