Nikolay Kostov Nikolay Kostov - 1 month ago 12
C# Question

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

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?

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
}
Comments