How and where to call Database.EnsureCreated and Database.Migrate?

后端 未结 5 2078
栀梦
栀梦 2020-11-28 04:49

I have a ASP.NET MVC 6 application, and i need to call the Database.EnsureCreated and Database.Migrate methods.

But where should I call the

5条回答
  •  旧时难觅i
    2020-11-28 05:35

    Just as a foreward you should read this from Rowan Miller:

    ... EnsureCreated totally bypasses migrations and just creates the schema for you, you can't mix this with migrations. EnsureCreated is designed for testing or rapid prototyping where you are ok with dropping and re-creating the database each time. If you are using migrations and want to have them automatically applied on app start, then you can use context.Database.Migrate() instead.

    According to answer here you need to add Globals.EnsureDatabaseCreated(); it to Startup.cs:

    Startup function in Startup.cs:

    public Startup(IHostingEnvironment env)
    {
        // Set up configuration sources.
        var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddEnvironmentVariables();
    
        if (env.IsDevelopment())
        {
            // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
                builder.AddApplicationInsightsSettings(developerMode: true);
        }
        Configuration = builder.Build();
        Globals.Configuration = Configuration;
        Globals.HostingEnvironment = env;
        Globals.EnsureDatabaseCreated();
    }
    

    And define Globals.EnsureDatabaseCreated() as follows:

    public static void EnsureDatabaseCreated()
        {
            var optionsBuilder = new DbContextOptionsBuilder();
            if (HostingEnvironment.IsDevelopment()) optionsBuilder.UseSqlServer(Configuration["Data:dev:DataContext"]);
            else if (HostingEnvironment.IsStaging()) optionsBuilder.UseSqlServer(Configuration["Data:staging:DataContext"]);
            else if (HostingEnvironment.IsProduction()) optionsBuilder.UseSqlServer(Configuration["Data:live:DataContext"]);
            var context = new ApplicationContext(optionsBuilder.Options);
            context.Database.EnsureCreated();
    
            optionsBuilder = new DbContextOptionsBuilder();
            if (HostingEnvironment.IsDevelopment()) optionsBuilder.UseSqlServer(Configuration["Data:dev:TransientContext"]);
            else if (HostingEnvironment.IsStaging()) optionsBuilder.UseSqlServer(Configuration["Data:staging:TransientContext"]);
            else if (HostingEnvironment.IsProduction()) optionsBuilder.UseSqlServer(Configuration["Data:live:TransientContext"]);
            new TransientContext(optionsBuilder.Options).Database.EnsureCreated();
        }
    

    To use context.Database.Migrate() see here or here.

提交回复
热议问题