Entity Framework 4.3.1 migrations always invokes default constructor and ignores connectionstring

做~自己de王妃 提交于 2019-12-05 18:26:16

The Update-database call is using the default constructor, so you have to modify that function. You mentioned you have a static class to do this, I couldn't figure out a way to make this work without a static helper.

 public static class Helper
    {
        public static string GetConnectionString()
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            builder.DataSource = @".\sqlexpress";
            builder.InitialCatalog = "migrateme";
            builder.IntegratedSecurity = true;
            builder.MultipleActiveResultSets = true;
            return builder.ConnectionString;
        }
    }

and then instead of calling the base constructor, I called the constructor with the custom string, and it created the correct database

public PocModel() : base(Helper.GetConnectionString())
{ 

}
nialljt

I had the same problem as you. However I found a solution that you said that you tried but didn't work. The following code did work for me. I found it here http://romiller.com/2012/02/09/running-scripting-migrations-from-code/

var configuration = new Configuration();
configuration.TargetDatabase = new DbConnectionInfo("Server=MyServer;Database=MyDatabase;Trusted_Connection=True;", 
    "System.Data.SqlClient");
var migrator = new DbMigrator(configuration);
migrator.Update();

For those who find that their connection string is ignored...

There appears to be a bug in this part of the framework

var configuration = new TMigrationsConfiguration();
configuration.TargetDatabase = new DbConnectionInfo(context.Database.Connection.ConnectionString,"System.Data.SqlClient");
var migrator = new DbMigrator(configuration);
migrator.Update();

Does not act the same as

var configuration = new TMigrationsConfiguration();
var migrator = new DbMigrator(configuration);
migrator.Configuration.TargetDatabase = new DbConnectionInfo(context.Database.Connection.ConnectionString,"System.Data.SqlClient");
migrator.Update();

That is - the Target database is ignored if changed after creating the migrator. You must set TargetDatabase before adding to the migrator.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!