【问题标题】:EF Core: how to insert new record with new multiple related records at onceEF Core:如何一次插入具有新的多个相关记录的新记录
【发布时间】:2020-08-08 10:03:51
【问题描述】:

我已经使用 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);

但以下消息引发了错误:

未找到实体类型“列表”。确保 实体类型已添加到模型中。

我该如何解决这个问题?

【问题讨论】:

  • 你通常会做newProduct.ProductImage = productImages; 然后只做await _context.AddAsync(newProduct); -> 你只添加父级,EF Core 会处理其余的事情
  • @CamiloTerevinto 没用!只是添加了产品,没有任何其他相关记录,如 ProductImage 不会插入数据库。
  • 听起来您的代码中发生了其他事情,您可以发布完整的代码吗?

标签: c# asp.net-core ef-core-3.1


【解决方案1】:

特别感谢@CamiloTerevinto,我找到了解决方案。

在执行 AddRange 之前,必须将相关实体分配给基础实体。 所以它会如下所示:

newProduct.ProductImage = productImages;
newProduct.ProductFile = productFiles;
newProduct.ProductAttribute = productAttributes;
newProduct.ProductFeature = productFeatures;
newProduct.ProductTag = productTags;

那么简单:

await _context.AddRangeAsync(newProduct);

【讨论】:

  • 请注意:如果您只在上下文中插入 一个 基本实体,则可以使用AddAsync 而不是AddRangeAsync。阅读 MS 的文档也很有趣:docs.microsoft.com/en-us/dotnet/api/… - 它说:“开始跟踪给定实体,以及尚未跟踪的任何其他可访问实体”
猜你喜欢
  • 1970-01-01
  • 2013-05-02
  • 2020-08-28
  • 1970-01-01
  • 2015-08-14
  • 2016-10-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-16
相关资源
最近更新 更多