我已经使用EF Core脚手架命令添加了DBContext,并且在我的模型中创建了以下实体。 每个产品将有一个以上的图像作为“ ProductImage”,这与具有ProductId外键的产品有关。
产品实体:
public partial class Product
{
public Product()
{
ProductImage = new HashSet<ProductImage>();
}
public int Id { get; set; }
public virtual ICollection<ProductImage> ProductImage { get; set; }
}
ProductImage实体:
public partial class ProductImage
{
public int Id { get; set; }
public int ProductId { get; set; }
public virtual Product Product { get; set; }
}
我想使用AddRangeAsync方法立即插入具有新图片的新产品。
所以我做到了:
var newProduct = new Product
{
CategoryId = product.CategoryId,
// ... other columns
};
var productImages = new List<ProductImage>();
productImages.Add(new ProductImage
{
Product = newProduct,
// ... other columns
});
然后将其全部插入:
await _context.AddRangeAsync(product, productImages);
但是以下消息引发了错误:
未找到实体类型“列表”。确保 实体类型已添加到模型中。
我该如何解决这个问题?
答案 0 :(得分:0)
特别感谢@CamiloTerevinto,我找到了解决方案。
在执行AddRange之前,必须将相关实体分配给基本实体。 因此它将如下所示:
newProduct.ProductImage = productImages;
newProduct.ProductFile = productFiles;
newProduct.ProductAttribute = productAttributes;
newProduct.ProductFeature = productFeatures;
newProduct.ProductTag = productTags;
然后简单地:
await _context.AddRangeAsync(newProduct);