How do I inject a connection string into an instance of IDbContextFactory?

后端 未结 3 774
暗喜
暗喜 2020-12-09 04:28

I\'m using Entity Framework 5 with Code First Migrations. I have a DataStore class which derives from DbContext:

public class DataS         


        
3条回答
  •  感动是毒
    2020-12-09 04:35

    For those for whom upgrading to Entity Framework 6 is viable, there's a new overload of the migration initialization that makes this much easier:

        // Parameters:
        //   useSuppliedContext:
        //     If set to true the initializer is run using the connection information from the
        //     context that triggered initialization. Otherwise, the connection information
        //     will be taken from a context constructed using the default constructor or registered
        //     factory if applicable.
        public MigrateDatabaseToLatestVersion(bool useSuppliedContext);
    

    Using this, you can run migrations with an injected DbContext as follows:

    Database.SetInitializer(new MigrateDatabaseToLatestVersion(useSuppliedContext: true));
    
    using (var context = kernel.Get())
        context.Database.Initialize(false);
    

提交回复
热议问题