我正在嘗試使用“添加”或“添加范圍”方法將串列添加到表中,但它們繼續覆寫最后一行,最后我在資料庫中只有一行。
查詢服務代碼:
private async Task AddProductTags(Product product, List<Process> processes)
{
foreach(var process in processes)
{
var tags = await _context.Tag.Where(tag => tag.ProcessId == process.ProcessId).ToListAsync();
List<ProductTag> productTags = new List<ProductTag>();
foreach(var tag in tags)
{
//ProductTag productTag = new ProductTag();
//productTag.ProductId = product.ProductId;
//productTag.Product = product;
//productTag.TagId = tag.TagId;
//productTag.Tag = tag;
//productTag.Value = "0";
//productTags.Add(productTag);
_context.ProductTag.Add(new ProductTag()
{
ProductId = product.ProductId,
Product = product,
TagId = tag.TagId,
Tag = tag,
Value = "0"
});
await _context.SaveChangesAsync();
};
//_context.ProductTag.AddRange(productTags);
//await _context.SaveChangesAsync();
}
}
如您所見,我一直在嘗試不同的事情。我一直在閱讀將物件初始化程式放入回圈中的解決方案的帖子,但我從一開始就這樣做了。如果我在回圈中除錯并停止,我已經檢查了插入第一行是否正常(使用“添加”方法),然后用下一個覆寫它。
我敢打賭這是一件愚蠢的事情,因為我仍在學習 EF Core,但我找不到錯誤。
更新
產品標簽類:
public class ProductTag
{
public int ProductId { get; set; }
public int TagId { get; set; }
public virtual Tag Tag { get; set; }
public virtual Product Product { get; set; }
public string Value { get; set; }
}
資料庫表配置:
public ProductTagConfiguration(EntityTypeBuilder<ProductTag> entityTypeBuilder)
{
entityTypeBuilder.HasKey(pt => new { pt.ProductId, pt.TagId });
entityTypeBuilder.Property(pt => pt.Value).IsRequired();
entityTypeBuilder
.HasOne(pt => pt.Product)
.WithOne(p => p.ProductTag);
entityTypeBuilder
.HasOne(pt => pt.Tag)
.WithOne(t => t.ProductTag);
}
uj5u.com熱心網友回復:
問題是資料庫設定中的錯誤配置:
public ProductTagConfiguration(EntityTypeBuilder<ProductTag> entityTypeBuilder)
{
entityTypeBuilder.HasKey(pt => new { pt.ProductId, pt.TagId });
entityTypeBuilder.Property(pt => pt.Value).IsRequired();
entityTypeBuilder
.HasOne(pt => pt.Product)
.WithOne(p => p.ProductTag); // HERE IT'S THE MISTAKE
entityTypeBuilder
.HasOne(pt => pt.Tag)
.WithOne(t => t.ProductTag); // AND HERE TOO
}
當我看到資料庫配置時,我意識到它出了什么問題。我將它設定為 1..1 關系,這是因為同一行正在更新。問題解決了,謝謝大家。
uj5u.com熱心網友回復:
假設 ProductTag 的 PK 等于 ProductId,您正在通過 foreach 行程更新相同的產品更改標簽。如果需要復制不同標簽的產品,則每次都需要生成新的ProductId。否則,您需要對所有標簽求和,最后將 ProductTag 添加到集合中
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/418695.html
標籤:
下一篇:插入觸發器之前包含錯誤的資料
