1. in Data folder, add a file called DutchSeeder.cs
2. in this file, for example
public class DutchSeeder
{
private readonly DutchContext context;
private readonly IHostingEnvironment hosting;
public DutchSeeder(DutchContext context, IHostingEnvironment hosting) {
this.context = context;
this.hosting = hosting;
}
public void Seed()
{
this.context.Database.EnsureCreated();
if (!this.context.Products.Any()) {
**read json file and add to DbSet(List)**
var filePath = Path.Combine(this.hosting.ContentRootPath, "Data/art.json");
var json = File.ReadAllText(filePath);
var products = JsonConvert.DeserializeObject<IEnumerable<Product>>(json);
this.context.AddRange(products);
var order = new Order()
{
OrderDate = DateTime.Now,
OrderNumber = "12345",
Items = new List<OrderItem>() {
new OrderItem(){
Product = products.First(),
Quantity = 5,
UnitPrice = products.First().Price
}
}
};
this.context.Add(order);
this.context.SaveChanges();
}
}
}
3. in Startup.cs,
in ConfigureServices method,
services.AddTransient<DutchSeeder>();
in Configure method,
if (env.IsDevelopment())
{
using (var scope = app.ApplicationServices.CreateScope()) {
var seeder = scope.ServiceProvider.GetService<DutchSeeder>();
seeder.Seed();
}
}