【问题标题】:How to migrate Db using EF in code instead of Nuget package manager console?如何在代码中使用 EF 而不是 Nuget 包管理器控制台迁移 Db?
【发布时间】:2013-06-27 03:48:50
【问题描述】:

我正在尝试在单元测试中创建一种测试方法,该方法将在数据库上应用迁移。所以我google了一段时间,找到了关于DbMigrator类的信息。以下是 EF 4.3 的示例用法:

var configuration = new Configuration();
var migrator = new DbMigrator(configuration);
migrator.Update();

这个不起作用,因为我使用的是 EF 5.0。所以我做了这样的事情:

DbMigrationsConfiguration configuration = new DbMigrationsConfiguration();
configuration.TargetDatabase = new DbConnectionInfo("***", "System.Data.SqlClient");
configuration.ContextType = typeof (EfContext);
//Dies here
var migrator = new DbMigrator(configuration);
migrator.Update();

但它会抛出异常 - Object reference not set to an instance of an object. 这是堆栈跟踪:

at System.Data.Entity.Migrations.Infrastructure.MigrationAssembly..ctor(Assembly migrationsAssembly, String migrationsNamespace)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
at CloudAdNet.Testing.UnitTests.Test.SeedTest() in c:\Users\maris.vigulis\Documents\Visual Studio 2012\Projects\CloudAdNetSoftware\CloudAdNet.Testing.UnitTests\Test.cs:line 19

有什么预付款吗?

【问题讨论】:

    标签: c# entity-framework code-first entity-framework-migrations


    【解决方案1】:

    1) 将您的Configuration 设为公开课程:

    public sealed class Configuration : DbMigrationsConfiguration<YourContextClassHere>
    

    2) 在下面的任何地方添加代码,这将运行最新的迁移并更新您的数据库:

    Configuration configuration = new Configuration();
    configuration.ContextType = typeof(YourContextClassHere);
    var migrator = new DbMigrator(configuration);
    
    //This will get the SQL script which will update the DB and will write it to debug
    var scriptor = new MigratorScriptingDecorator(migrator);
    string script = scriptor.ScriptUpdate(sourceMigration: null, targetMigration: null).ToString();
    Debug.Write(script);
    
    //This will run the migration update script and will run Seed() method
    migrator.Update();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多