EntityFrameworkCore: How to initialize a Database and seed it the first time user uses an application

走远了吗. 提交于 2019-12-07 17:10:35

问题


I have build a project using Microsoft Visual Studio 2015 and EntityFrameworkCore.

I have seed manually a couple of dummy data and I was developing my solution. Now, I want to deploy the in the server, but I get the problem that by starting the application the first time, it crash since it does not find a data base and data.

I have googled and I find the solution for Visual Studio 2013 and previous using the CreateDatabaseIfNotExists class that need the package: System.Data.Entity (http://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-first.aspx), however, such classes and packages do not exist in EntityFrameworkCore.

How does I create and populate a database with at least one row if user is using my application by the first time in EntityFrameworkCore?

or which is the equivalent to System.Data.Entity in Entity Framework Core?


回答1:


Rowan Miller says that ApplyMigrations is enough to create database (if not exist) and apply all (nesessary) migrations.

Create method like this:

public void CreateDbAndSampleData(IServiceProvider applicationServices)
{
    using (var serviceScope = applicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
    {
        using (var db = serviceProvider.GetService<ApplicationDbContext>()) 
        {
            // This will [try to] create database
            // and apply all necessary migrations
            db.Database.AsRelational().ApplyMigrations();

            // then you can check for existing data and modify something
            var admin = db.Users.Where(x => x.Name == "Superadmin").FirstOrDefault();
            if (admin == null)
            {
                db.Users.Add(new User {...});
                db.SaveChanges();
            }
        }
    }
}

And call it from your Startup.cs, at end of Configure method:

CreateDbAndSampleData(app.ApplicationServices);

This code will run on every app startup, so you need to be accurate and do not overwrite any non-critical data changes (like changing Users's comment etc)

You can use MusicStore app as a sample: Startup.cs and SampleData.cs



来源:https://stackoverflow.com/questions/40549735/entityframeworkcore-how-to-initialize-a-database-and-seed-it-the-first-time-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!