在实体框架7 RC 1和ASP.NET MVC 6号种子的初始数据 [英] Seed initial data in Entity Framework 7 RC 1 and ASP.NET MVC 6

查看:296
本文介绍了在实体框架7 RC 1和ASP.NET MVC 6号种子的初始数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看来,在实体框架7有种子数据没有原生支持,但( https://github.com/ ASPNET /的EntityFramework /问题/ 629 )。

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

有没有 DbMigrationsConfiguration 类,没有在微软提供的模板代码种子方法。

那么如何在ASP.NET种子数据MVC 6使用实体框架7 RC 1的web应用程序?

推荐答案

我找到了一个临时解决办法为自己。

I've found a temporary workaround for myself.

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

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

要使用它把应用.SeedData(); 应用程序启动类的配置法线(位于在文件中的web项目名为 Startup.cs )。

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
}

这篇关于在实体框架7 RC 1和ASP.NET MVC 6号种子的初始数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆