Seed initial data in Entity Framework 7 RC 1 and ASP.NET MVC 6(在 Entity Framework 7 RC 1 和 ASP.NET MVC 6 中播种初始数据)
问题描述
在 Entity Framework 7 中似乎还没有对种子数据的原生支持(https://github.com/aspnet/EntityFramework/issues/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类,没有Seed方法.
There is no DbMigrationsConfiguration class, no Seed method in the template code provided by Microsoft.
那么如何在使用 Entity Framework 7 RC 1 的 ASP.NET MVC 6 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();
}
}
要使用它,请将 app.SeedData(); 行放在应用程序 Startup 类的 Configure 方法中(位于 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
}
这篇关于在 Entity Framework 7 RC 1 和 ASP.NET MVC 6 中播种初始数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Entity Framework 7 RC 1 和 ASP.NET MVC 6 中播种初始数据
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 使用 rss + c# 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
