【发布时间】:2018-03-20 19:23:23
【问题描述】:
我打算托管我的 asp.net mvc 应用程序。而且我希望我的客户能够从控制器的方法中运行种子方法。
这就是我现在拥有的:
public class Configuration : DbMigrationsConfiguration<CUDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(CUDbContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//if (context.Database.Exists()) return;
#region Some sample data
context.Persons.AddOrUpdate(
new Person
{
//some information
});
#endregion
public void RunSeed()
{
var context = new CUDbContext();
Seed(context);
}
}
这就是我从控制器调用种子方法的方式:
public ActionResult Seed()
{
var db = new DAL.Migrations.Configuration {ContextType = typeof(CUDbContext)};
var migrator = new DbMigrator(db);
var scriptor = new MigratorScriptingDecorator(migrator);
var script = scriptor.ScriptUpdate(sourceMigration: null, targetMigration: null).ToString();
//Debug.Write(script);
migrator.Update();
return RedirectToAction("Index");
}
我的控制器的方法是基于this 发帖。
但是,当我使用种子方法点击控制器时,数据库没有更新。
任何建议如何工作。问题是客户端将没有 Visual Studio 去包管理器控制台运行 update-database 命令。所以我希望能够从控制器的方法中做到这一点。
我也在控制器中尝试过,但没有成功:
public ActionResult Seed()
{
var db = new DAL.Migrations.Configuration {ContextType = typeof(CUDbContext)};
db.RunSeed();
//var migrator = new DbMigrator(db);
//var scriptor = new MigratorScriptingDecorator(migrator);
//var script = scriptor.ScriptUpdate(sourceMigration: null, targetMigration: null).ToString();
////Debug.Write(script);
//migrator.Update();
return RedirectToAction("Index");
}
【问题讨论】:
标签: c# asp.net asp.net-mvc entity-framework