0

我正在尝试在单元测试中创建一个测试方法,它将在数据库上应用迁移。所以我用谷歌搜索了一段时间,找到了有关该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

有预支吗?

4

1 回答 1

0

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();
于 2013-06-27T09:17:08.837 回答