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

entity-framework-core

Question

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
3
5/15/2017 5:40:09 PM

Popular Answer

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

2
11/14/2016 2:40:53 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow