Seeding database imlementation of EF6 not working in EntityFrameworkcore

旧城冷巷雨未停 提交于 2019-12-11 05:16:21

问题


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

Here is my code

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 doesn't seem to like DropCreateDatabaseIfModelChanges keyword.Could somebody show me an example of how seeding is done using EntityFrameworkcore.


回答1:


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

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).

Implementing Seeding EF Core 1.0



来源:https://stackoverflow.com/questions/40709274/seeding-database-imlementation-of-ef6-not-working-in-entityframeworkcore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!