在StartUp.cs里面,添加Seed方法
public static void Seed(IApplicationBuilder applicationBuilder) { using (var serviceScope = applicationBuilder.ApplicationServices.GetRequiredService<IServiceScopeFactory>() .CreateScope()) { AppDbContext context = serviceScope.ServiceProvider.GetService<AppDbContext>(); if (!context.Products.Any()) { // 这里做操作 } context.SaveChanges(); } }
在Configure方法添加引用
Seed(app);