EF6 的播种数据库实现在 EntityFrameworkcore 中不起作用 [英] Seeding database imlementation of EF6 not working in EntityFrameworkcore

查看:32
本文介绍了EF6 的播种数据库实现在 EntityFrameworkcore 中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Entity Framework 6 中播种的实现代码似乎与 EntityFramework 核心兼容

My implementation code for seeding in Entity Framework 6 dosent seem compatible with EntityFramework core

这是我的代码

public class CustomerOrderSeedData : DropCreateDatabaseIfModelChanges<CustomerOrderEntities>
    {
        protected override void Seed(CustomerOrderEntities context)
        {

            GetOrderDetails().ForEach(od => context.OrdersDetails.Add(od));

            context.Commit();
        }

 private static List<OrdersDetails> GetOrderDetails()
        {
            return new List<OrdersDetails>
            {
                new OrdersDetails {
                    OrderId = 1,
                    ProductId = 1,
                    Quantity = 10,
                    UnitPrice = 12,
                    Discount = 3

                },
                new OrdersDetails {
                     OrderId = 1,
                    ProductId = 2,
                    Quantity = 3,
                    UnitPrice = 4,
                    Discount = 2
                }
       }
}

EntityFrameworkCore 似乎不喜欢 DropCreateDatabaseIfModelChanges 关键字.有人可以向我展示如何使用 EntityFrameworkcore 完成播种的示例.

EntityFrameworkCore doesn't seem to like DropCreateDatabaseIfModelChanges keyword.Could somebody show me an example of how seeding is done using EntityFrameworkcore.

推荐答案

是的.您不能将 EF 6.X 实现与 EF 核心一起使用.B'cos EF 核心为此具有不同的 API.

Yes.You cannot use EF 6.X implementation with the EF core.B'cos EF core is having different APIs for that.

您可以在 Startup.Configure() 中的服务范围内运行播种代码,如下所示.

You can run the seeding code within a service scope in Startup.Configure() as shown below.

using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
       var context = serviceScope.ServiceProvider.GetService<MyContext>();       
       context.Database.Migrate();
       context.EnsureSeedData();
 }

这是您可以查看上述代码片段的完整实现的链接(参见播种部分).

Here is the link which you can see complete implementation of the above code snippet (see under the Seeding section).

实现播种 EF Core 1.0

这篇关于EF6 的播种数据库实现在 EntityFrameworkcore 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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