Seed initial data in Entity Framework 7 RC 1 and ASP.NET MVC 6

asp.net-core-mvc c# entity-framework entity-framework-core seeding

Question

It seems that in Entity Framework 7 there is no native support for seed data yet (https://github.com/aspnet/EntityFramework/issues/629).

There is no DbMigrationsConfiguration class, no Seed method in the template code provided by Microsoft.

So how to seed data in ASP.NET MVC 6 web application that uses Entity Framework 7 RC 1?

Accepted Answer

I've found a temporary workaround for myself.

We can create a method SeedData that extends the IApplicationBuilder then gets an instance of our database context class through GetService method and uses it for seeding the data.

Here is how my extension method looks like:

using Microsoft.AspNet.Builder;
using Microsoft.Extensions.DependencyInjection;

public static class DataSeeder
{
    // TODO: Move this code when seed data is implemented in EF 7

    /// <summary>
    /// This is a workaround for missing seed data functionality in EF 7.0-rc1
    /// More info: https://github.com/aspnet/EntityFramework/issues/629
    /// </summary>
    /// <param name="app">
    /// An instance that provides the mechanisms to get instance of the database context.
    /// </param>
    public static void SeedData(this IApplicationBuilder app)
    {
        var db = app.ApplicationServices.GetService<ApplicationDbContext>();

        // TODO: Add seed logic here

        db.SaveChanges();
    }
}

To use it put app.SeedData(); line in the Configure method of the application Startup class (located in the web project in file called Startup.cs).

// This method gets called by the runtime.
// Use this method to configure the HTTP request pipeline.
public void Configure(
    IApplicationBuilder app,
    IHostingEnvironment env,
    ILoggerFactory loggerFactory)
{
    app.SeedData();

    // Other configuration code
}

Popular Answer

For EF Core RTM 1.0 and ASP.NET Core RTM 1.0

First create the seed method. Here because we are out the scope of the current request, we must create it manulally:

using System.Collections.Generic;
using System.Linq;
using Core1RtmEmptyTest.Entities;
using Microsoft.Extensions.DependencyInjection;

namespace Core1RtmEmptyTest.Migrations
{
    public static class ApplicationDbContextSeedData
    {
        public static void SeedData(this IServiceScopeFactory scopeFactory)
        {
            using (var serviceScope = scopeFactory.CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
                if (!context.Persons.Any())
                {
                    var persons = new List<Person>
                    {
                        new Person
                        {
                            FirstName = "Admin",
                            LastName = "User"
                        }
                    };
                    context.AddRange(persons);
                    context.SaveChanges();
                }
            }

        }
    }
}

Then specify the correct life time of the ApplicationDbContext

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(ServiceLifetime.Scoped);

And finally call the SeedData() method from the Configure method

public void Configure(IServiceScopeFactory scopeFactory)
{
    scopeFactory.SeedData();


Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why