gpt4 book ai didi

c# - 从 Controller 运行种子方法

转载 作者:行者123 更新时间:2023-11-30 18:16:24 25 4
gpt4 key购买 nike

我打算托管我的 asp.net mvc 应用程序。我希望我的客户端能够从 Controller 的方法运行种子方法。

这是我现在拥有的:

   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);
}
}

这就是我从 Controller 调用 seed 方法的方式:

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");
}

我的 Controller 的方法是基于 this发布。

但是,当我使用 seed 方法点击 Controller 时,数据库没有得到更新。

关于它如何工作的任何建议。事情是客户端不会有 visual studio 去包管理器控制台运行更新数据库命令。所以我希望能够从 Controller 的方法中做到这一点。

我也在 Controller 中试过这个,但没有用:

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");
}

最佳答案

您应该重构您的代码并将种子内容移动到单独的方法中,在此示例中 - 静态 Seeder.Seed。然后你可以简单地从任何地方调用它,不费吹灰之力,把你的上下文实例传递给它。此外,您的第一段代码可能只运行迁移,根本不调用 Seed:

public class Seeder
{
public static void Seed(CUDbContext context)
{
//your seed logic...
}
}

public class Configuration : DbMigrationsConfiguration<CUDbContext>
{
//other stuff...
protected override void Seed(CUDbContext context)
{
Seeder.Seed(context);
}
}

Controller :

public ActionResult Seed()
{
using(var context = new CUDbContext())
{
Seeder.Seed(context);
}
return Content("Ok")
}

关于c# - 从 Controller 运行种子方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46648901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com