EntityFramework代码优先的自定义连接字符串和迁移

当我使用默认的连接字符串(从中读取app.config)创建上下文时,将创建数据库并进行迁移-基本上,所有操作都是有序的。而以编程方式(使用SqlConnectionStringBuilder)创建连接字符串时:


当数据库不存在时,不会创建数据库(场景A);

CreateDbIfNotExists()创建数据库模型的最新版本,但不调用迁移机制(场景B)。

在A明显- -一个异常时,我希望访问数据库,抛出它不存在。在B数据库中创建的迁移机制没有正确调用,就像标准连接字符串中那样。


app.config:“ Data Source=localhost\\SQLEXPRESS;Initial Catalog=Db13;User ID=xxx;Password=xxx”


建造者:


sqlBuilder.DataSource = x.DbHost;

sqlBuilder.InitialCatalog = x.DbName;

sqlBuilder.UserID = x.DbUser;

sqlBuilder.Password = x.DbPassword;

初始值设定项:


Database.SetInitializer(

    new MigrateDatabaseToLatestVersion<

        MyContext,

        Migrations.Configuration

    >()

);

规格:实体框架:5.0,数据库:SQL Server Express 2008


暮色呼如
浏览 790回答 3
3回答

蝴蝶刀刀

如果您的迁移无法正常进行,请尝试Database.Initialize(true)在DbContext ctor中进行设置。public CustomContext(DbConnection connection): base(connection, true)&nbsp; &nbsp;&nbsp;{&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Database.Initialize(true);&nbsp; &nbsp;&nbsp;}&nbsp; &nbsp;&nbsp;我在迁移中也遇到类似的问题。在我的解决方案中,我必须始终在ctor中设置数据库初始化程序,如下所示public CustomContext(DbConnection connection): base(connection, true)&nbsp; &nbsp;&nbsp;{&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Database.SetInitializer(new CustomInitializer());&nbsp; &nbsp; &nbsp; &nbsp; Database.Initialize(true);&nbsp; &nbsp;&nbsp;}&nbsp; &nbsp;&nbsp;在自定义初始化程序中,您必须实现InitalizeDatabase(CustomContex context)方法,例如。class CustomInitializer : IDatabaseInitializer<CustomContext>{&nbsp; &nbsp; public void InitializeDatabase(CustomContext context)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (!context.Database.Exists || !context.Database.CompatibleWithModel(false))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var configuration = new Configuration();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var migrator = new DbMigrator(configuration);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; migrator.Configuration.TargetDatabase = new DbConnectionInfo(context.Database.Connection.ConnectionString, "System.Data.SqlClient");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var migrations = migrator.GetPendingMigrations();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (migrations.Any())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var scriptor = new MigratorScriptingDecorator(migrator);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string script = scriptor.ScriptUpdate(null, migrations.Last());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!String.IsNullOrEmpty(script))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; context.Database.ExecuteSqlCommand(script);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP