Skip to content

Instantly share code, notes, and snippets.

@josheinstein
Created April 16, 2014 20:07
Show Gist options
  • Save josheinstein/10927687 to your computer and use it in GitHub Desktop.
Save josheinstein/10927687 to your computer and use it in GitHub Desktop.
When using Entity Framework code-first with LINQPad (or any time an EF DbContext is subclassed) any calls to Database.SetInitializer with the base class is effectively ignored. This is especially irritating with LINQPad which needs to subclass the context class in order to work the way it is designed. This means that if you called Database.SetIn…
public class MyDbContext : DbContext
{
/// <summary>
/// Initializes a new instance of the <see cref=“T:MyDbContext"/> class.
/// </summary>
public MyDbContext( )
: base( "DefaultConnection" )
{
// This must be called in the *instance* constructor
// and not the static constructor as is normally done.
DisableDatabaseInitialization( );
}
/// <summary>
/// Calls the <see cref="T:Database.SetInitializer[T]"/> method using the concrete type of the
/// current instance to disable the EF default behavior of creating a database schema that
/// does not already exist.
/// </summary>
/// <remarks>
/// Typically, one would call <see cref="T:Database.SetInitializer[T]"/> with a compile-time type
/// of the context class. However, if the context type is not sealed, it is possible that a
/// subclass will be used instead, rendering the call to SetInitializer useless. This can be the
/// case when using a EF data context assembly with LINQPad, which creates a subclass of the
/// context class using the code typed into the interface. This can result in a database being
/// created, even though the intent was to NOT create a database.
/// This method uses reflection to call the SetInitializer method with the runtime type of the
/// current instance. This should be called immediately in the instance constructor, before a
/// connection is made to the underlying database server.
/// </remarks>
private void DisableDatabaseInitialization( )
{
var databaseType = typeof( Database );
var setInitializer = databaseType.GetMethod( "SetInitializer", BindingFlags.Static | BindingFlags.Public );
var thisType = GetType( );
var setInitializerT = setInitializer.MakeGenericMethod( thisType );
setInitializerT.Invoke( null, new object[] { null } );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment