<分区>
似乎在 Entity Framework 7 中还没有对种子数据的原生支持(https://github.com/aspnet/EntityFramework/issues/629)。
微软提供的模板代码中没有DbMigrationsConfiguration
类,也没有Seed
方法
那么如何在使用 Entity Framework 7 RC 1 的 ASP.NET MVC 6 Web 应用程序中播种数据?
<分区>
似乎在 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/