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

守給你的承諾、 提交于 2019-12-05 20:55:35

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

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