When using the Entity Framework if you want to mess with your entities before they persist to the database one popular way to do it is to hook into SavingChanges from the OnContextCreated method of your Entities ObjectContext like so:

public partial class SomethingEntities
{
partial void OnContextCreated()
{
this.SavingChanges += new EventHandler(OnSavingChanges);
}

public void OnSavingChanges(object sender, System.EventArgs e)
{
//Do stuff
}
}

I was trying to do exactly this but was having a problem. The gosh darn thing wouldn’t fucking fire. In fact, none of the constructors on my Entities ObjectContext were firing. My controls were dancing around all over the place selecting and updating data but nay a constructor to be called.

My EntityDataSource looked like this:

<asp:EntityDataSource ID=”DataSource” ConnectionString=”name=SomethingEntities” DefaultContainerName=”SomethingEntities”
EnableDelete=”True” EnableInsert=”True” EnableUpdate=”True” EntitySetName=”EntityName” runat=”server” />

I was using both the ConnectionString and the DefaultContainerName property as initialization parameters to get the DataSource going. Turns out this wasn’t the right thing to do because when configured this way the DataSource never got my Entities ObjectContext to fire its constructors. I got it to work after some head scratching by changing it to:

<asp:EntityDataSource ID=”DataSource” ContextTypeName=”Namespace.SomethingEntities”
EnableDelete=”True” EnableInsert=”True” EnableUpdate=”True” EntitySetName=”EntityName” runat=”server” />

By using the ContextTypeName property instead of the ConnectionString and DefaultContainerName properties everything seemed to work. A constructor on my Entities ObjectContext was called which in turn called OnContextCreated which hooked up my SavingChanges method which now gets called when it should before changes are persisted to the database.

Problem solved.

2 Responses to “The Entity Framework, EntityDataSource, OnContextCreated() and OnSavingChanges(…) – ObjectContext Constructor Not Firing OnContextCreated”

  1. samerpaul says:

    Wow, thank you! I have been struggling with this all morning–I had no idea why my breakpoints were never being hit for the SavingChanges event.

  2. Rolf says:

    awesome, It wouldn’t fire for me either and I was about to pull my hair out..
    thanks,,

Leave a Reply