Database.SetInitializer to null not working Entity Framework 4.3.1 Code First

前端 未结 2 1726
暗喜
暗喜 2020-12-10 20:03

I have a context class that inherits from an abstract base AuditableDbContext : DbContext. The AuditableDbContext takes two parameters, one for the

相关标签:
2条回答
  • 2020-12-10 20:18

    You will need to do this in the static constructor or better still PRIOR to instantiating the Context.

    static MyDbContext() {
        Database.SetInitializer<MyDbContext>(null);
    }
    
    0 讨论(0)
  • 2020-12-10 20:27

    Sorry to reply to such an old question, especially one that is marked as answered, but it has plagued me and I wanted to offer a solution regardless.

    The problem is that LINQPad creates a subclass of your DbContext class. So when you called Database.SetInitializer<MyDbContext>(null), that will work as long as you are creating an instance of MyDbContext. But by design, LINQPad compiles your code into a class that derives from MyDbContext. If you make MyDbContext sealed, LINQPad won't be able to use it.

    The workaround is to use reflection to call Database.SetInitializer in the instance constructor of MyDbContext. This means you're unnecessarily calling it for every instance of the context, but it won't hurt anything. But this allows you to use this.GetType() to get access to the subclass that LINQPad creates and then you can use reflection to call SetInitializer.

    Would be nice if a non-generic version of the method was added though.

    This Gist has an example of using reflection to call Database.SetInitializer.

    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 } );
    
    0 讨论(0)
提交回复
热议问题