我有一个asp.net core 2.2项目,我正在为Entity Framework Core创建第一个迁移,并且我想读取文件图像的标题并创建一个对象列表,以使用所述对象列表为数据库播种,我有一个课
从接口IProductRepository继承的表示该类包含一个对象产品列表,我一直在尝试查找是否可以使用EF Core 2.2播种产品列表?没有在OnModelCreating的重载上使用任何静态方法?还是在创建第一个迁移后?
public class ProductRepository : IProductRepository
public interface IProductRepository
{
Product AddProduct(Product p);
Product Delete(Guid Id);
Product UpdateProduct(Product p);
IEnumerable<Product> GetAllProduct();
Product GetProduct(Guid id);
IEnumerable<Product> GetProductBy(ProductType type);
}```
```public List<Product> productsList = new List<Product>();```
答案 0 :(得分:0)
对于任何有同样问题的人,我已经找到了一个解决方案,不久前注入接口并以编程方式保存迁移,以避免冲突,删除任何保存的迁移......它会起作用。并且不要进行手动迁移
{
public static bool InitializeDB(this AppDbContext context, IProductRepository productRepositoryMock = null, IProductRepository mock= null)
{
var items = productRepositoryMock.GetAllProducts();
int count = 0;
foreach (var item in items)
{
var found = context.Products.Select(x => x.ProductName == item.ProductName).Any();
if (!found)
{
context.Products.Add(item);
count++;
}
}
context.SaveChanges();
context.initialized = 0x01;
return count > 0;
}
public static bool EnsureDatabaseIsSeeded(this IApplicationBuilder applicationBuilder, IProductRepositoryMock mock, IHostingEnvironment env, bool autoMigrateDatabase)
{
// seed the database using an extension method
using (var serviceScope = applicationBuilder.ApplicationServices
.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var ctx= serviceScope.ServiceProvider.GetService<AppDbContext>();
if (autoMigrateDatabase)
{
ctx.Database.Migrate();
}
var res = ctx.InitializeDB(mock);
serviceScope.ServiceProvider.GetService<AppDbContext>().Database.Migrate();
return res;
}
}
}