【发布时间】:2019-07-31 13:11:52
【问题描述】:
Soo...我有Product 的这个简单模型:
public class Product {
public int Id { get; set; }
// Other things
public ICollection<ProductAttribute> ProductAttributes { get; set; }
}
还有ProductAttributes 和ProductId 和Name 作为多字段键。
public class ProductAttribute {
public int? ProductId { get; set; } // Key
public ProductAttributeName? Name { get; set; } // Key
public string Value { get; set; }
}
在我的 WebAPI 项目中,我有这个方法:
public async Task<IActionResult> Patch(Product product) {
var productExist = await _context.Products.AnyAsync(a => a.Id == product.Id);
if (!productExist) return NotFound(product.Id);
_context.Products.Update(product);
await _context.SaveChangesAsync();
return Ok();
}
我假设如果有人在 productAttributes 中发送我的 JSON 和不同的数据,我应该将值切换到完全覆盖的新值
或删除旧值。就像在这个例子中
OldProduct
* Name
* ProductAttributes:
* Value 1
* Value 2
NewProduct
* Name
* ProductAttributes:
* Value 2
* Value 3
所以Value1 应该被删除,Value3 应该被添加。但相反,我在SaveChangesAsync() 上遇到了一个例外:
System.ArgumentException: 'An item with the same key has already been added. Key: System.Object[]'
我猜可能是因为它正在尝试添加Value2,但它已经存在。
我应该如何正确更新导航属性?
@更新
感谢@cjens19,我只是更改了更新方法并使用了 Automapper:
public async Task<IActionResult> Patch(Product product) {
var productFromDb = await _context.Products.Include(p => p.ProductAttributes).SingleOrDefaultAsync(product1 => product1.Id == product.Id);
if (productFromDb == null) return NotFound(product.Id);
Mapper.Map(product, productFromDb);
await _context.SaveChangesAsync();
return Ok();
}
【问题讨论】:
标签: c# asp.net-core .net-core entity-framework-core