The answer to this problem is to edit the T4 Template to put in a method call at the end of the Constructor.
This method, in the context of partial classes generated by a template, needs to be a partial method.
The template needs to contain a definition for the partial method.
Then your custom partial class can implement that method and it will be called by the Constructors defined in the generated partial class - now you can regenerate that partial class as many times as you like and be guranteed that the partial method will always be called - assuming no one edits the template.
If someone does edit the template and removes the definition of the partial method, then you will get a compiler error - easy to fix.
If someone edits the template and removes the call to the partial method from the Constructor, then unfortunately, the compiler can't help you - something to be aware of!
Here is my solution in tid-bits:
A snippet of the constructor and partial method definition in the T4 Template code 'MyApp.Context.tt' (see here for a great explanation of T4 syntax and its use within the EntityFramework):
public <#=code.Escape(container)#>(string connectionString)
: base(connectionString, ContainerName)
{
<#
WriteLazyLoadingEnabled(container);
#>
// Call the OnContextCreated() method to perform any necessary 'post creation' setup
OnContextCreated();
}
// Define the OnContextCreated partial method so that the accompanying partial Context
// class can implement this method.
partial void OnContextCreated();
The custom partial class which implements the partial method and wires up the event handler:
public partial class MyAppContext
{
/// <summary>
/// Performs all 'post creation' operations for the MyAppContext
///
/// *********************************
/// NOTE: If you get a compiler error:
/// 'No defining declaration found for implementing declaration of partial method 'OnContextCreated()'
/// then it is likely that the partial class MyApp.Context.cs does not contain a corresponding
/// definition for the partial method OnContextCreated().
/// This can occur if the MyApp.Context.tt template no longer generates the definition.
/// SOLUTION: Edit the MyApp.Context.tt T4 template to ensure that that partial method is defined AND
/// that it is called from EACH MyAppContext() constructor.
/// *********************************
///
/// </summary>
partial void OnContextCreated()
{
// Register the event handler
this.Connection.StateChange += Connection_StateChange;
}
}