在Entity Framework 7 RC 1和ASP.NET MVC 6中播种初始数据

Nik*_*tov 16 c# entity-framework seeding entity-framework-core asp.net-core-mvc

似乎在Entity Framework 7中还没有对种子数据的原生支持(https://github.com/aspnet/EntityFramework/issues/629).

Microsoft提供的模板代码中没有DbMigrationsConfiguration类,没有Seed方法.

那么如何在使用Entity Framework 7 RC 1的ASP.NET MVC 6 Web应用程序中播种数据呢?

Nik*_*tov 15

我为自己找到了一个临时的解决方法.

我们可以创建一个方法SeedData,通过方法扩展IApplicationBuilder然后获取我们的数据库上下文类的实例,GetService并使用它来播种数据.

这是我的扩展方法的样子:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

要使用它,请将app.SeedData();line放在Configure应用程序Startup类的方法中(位于调用文件中的web项目中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
}
Run Code Online (Sandbox Code Playgroud)


Vah*_*idN 6

适用于EF Core RTM 1.0和ASP.NET Core RTM 1.0

首先创建种子方法.这里因为我们不在当前请求的范围内,所以我们必须创建它:

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();
                }
            }

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后指定ApplicationDbContext的正确生命周期

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(ServiceLifetime.Scoped);
Run Code Online (Sandbox Code Playgroud)

最后SeedData()Configure方法中调用方法

public void Configure(IServiceScopeFactory scopeFactory)
{
    scopeFactory.SeedData();
Run Code Online (Sandbox Code Playgroud)