c# - Entity Framework 7 RC 1 和 ASP.NET MVC 6 中的种子初始数据

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

<分区>

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

微软提供的模板代码中没有DbMigrationsConfiguration类,也没有Seed方法

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

最佳答案

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

我们可以创建一个扩展 IApplicationBuilder 的方法 SeedData,然后通过 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();
    }
}

要使用它,请将 app.SeedData(); 行放在应用程序 Startup 类(位于 Web 项目中)的 Configure 方法中在名为 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
}

关于c# - Entity Framework 7 RC 1 和 ASP.NET MVC 6 中的种子初始数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34536021/

相关文章:

c# - 结构是否可以序列化

C# 通过两个日期将时间写为字符串

c# - 使用 C# 在 MYSQL 中声明局部变量时发生 fatal error

c# - 在 EF 6 中找不到 HasOne

entity-framework - 如何在调用 'Update-Database' 之前查看 EF Code First Migrations 更改

c# - 在 ASP.Net Core 依赖注入(inject)中删除服务

c# - 网络核心 : Convert String to TagBuilder

asp.net-core-mvc - 从 .Net Core 1.0.0 升级到 1.1.0 时出错

c# - 具有 2 个参数的存储过程

sql-server - 如何增加 Entity Framework 和Sql Server之间的超时 session