我正在尝试在单元测试中创建一个测试方法,该方法将在数据库上应用迁移。所以我用谷歌搜索了一段时间,找到了关于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.
这是stacktrace:
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
任何进展?
答案 0 :(得分:0)
1)将你的Configuration
作为公共课:
public sealed class Configuration : DbMigrationsConfiguration<YourContextClassHere>
2)添加以下代码的任何位置,这将运行最新的迁移并更新您的db:
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();