如何通过CodeFirst迁移更快地在控制器中手动生成数据库表?

时间:2018-10-17 18:16:03

标签: c# asp.net asp.net-mvc ef-code-first ef-migrations

我首先使用C#和MVC代码启动了自定义CMS。我添加了一个名为Setup的控制器,并在设置控制器操作GenrateDatabase中获得了DatabaseName初始目录用户ID和数据库密码,之后生成了数据库连接字符串并在web.config中对其进行了更新,并在下面的代码中运行了seed方法。

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult GenrateDatabase([Bind(Include = "DataSource,InitialCatalog,UserId,Password")] Database database)
    {
        if (ModelState.IsValid)
        {
            if (database.GenrateDatabase())
            {
                return RedirectToAction("Register");
            }
        }
        ModelState.AddModelError("", "Mmm, something went wrong, Please check your data and try again.");
        return View(database);
    }

我的数据库类是:

public class Database
{
    [Required]
    public string DataSource { get; set; }

    [Required]
    public string InitialCatalog { get; set; }

    [Required]
    public string UserId { get; set; }

    [Required]
    public string Password { get; set; }

    private ApplicationDbContext db = new ApplicationDbContext();

    //$"Data Source={DataSource};Initial Catalog={InitialCatalog};User Id ={UserId}; Password = {Password};";
    private string ConnectionString => $"Data Source=.;Initial Catalog=Store;Integrated Security=SSPI";

    public bool GenrateDatabase()
    {
        var configuration = WebConfigurationManager.OpenWebConfiguration("~");
        var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
        section.ConnectionStrings["goomooshCNSdb"].ConnectionString = ConnectionString;
        configuration.Save();
        return (GenrateTables()) ? true : false;
    }

    private bool GenrateTables()
    {
        if (db.Database.Exists())
        {
            //var configuration = new DbMigrationsConfiguration();
            Migrations.Configuration configuration = new Migrations.Configuration();
            configuration.ContextType = typeof(ApplicationDbContext);
            var migrator = new DbMigrator(configuration);
            migrator.Configuration.TargetDatabase = new DbConnectionInfo(ConnectionString, "System.Data.SqlClient");
            var migrations = migrator.GetPendingMigrations();
            if (migrations.Any())
            {
                var scriptor = new MigratorScriptingDecorator(migrator);
                var script = scriptor.ScriptUpdate(null, migrations.Last());
                if (!string.IsNullOrEmpty(script))
                {
                    db.Database.ExecuteSqlCommand(script);
                    return true;
                }
            }
        }
        return false;
    }
}

当我运行我的项目并输入数据并提交表单时,所有代码都可以正常运行,但是问题是db.Database.ExecuteSqlCommand(script);花费太多时间,可能在10分钟后才完成。

当我在SQL Server上检查数据库时,代码创建了所有表,并且需要执行所有操作,但是代码从未重定向到注册操作。

如何像Wordpress或其他CMS一样更快地创建此类和方法?

0 个答案:

没有答案