问题
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