ObjectContext.SaveChanges is now Virtual/Overridable in EF4

Last summer, I asked this question in a thread in the MSDN forums:

So is there anyway to completely override savechanges - just replace it with your own code if for some reason you wanted to?

The answer was no.

As I am digging deeper and deeper into EF4 while I write the 2nd edition of Programming Entity Framework, I learned that the answer has changed to yes!

Visual Basic 
Public Overridable Function SaveChanges ( _
    options As SaveOptions _
) As Integer

C# 
public virtual int SaveChanges(
    SaveOptions options
)

Here is the topic in the .NET 4.0 Beta 1 Documentation: http://msdn.microsoft.com/en-us/library/dd395500(VS.100).aspx

This is not a capability to take lightly. If you peek into the SaveChanges method in Reflector, there’s a lot of logic you want to consider.

The provider (e.g. SqlClient) does most of the grunt work through the Update method of the IEntityAdapter interface.

SaveChanges wraps that with transactions and connections etc. So you could completely rethink how this works or plug in your own framework logic.

It is another door opening very widely on the possibilities of EF’s extensibility.

I want to point out a nod to Jiri Cincura who was on the team that added Entity Framework support for the Firebird provider. I did a web search after I started playing with overriding SaveChanges and saw that he had made a note of this back at the end of June.

No comments (yet...)

Leave a Comment