Disable database initiatization in LinqPad

11 Aug 2017

linqpad

Original code gist

JIC copy

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 } );
    }
}

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.