我正在使用ASP.NET Core 5 Web API,并尝试将新的C#记录用作我的模型类。但是,每当我使用with
表达式更新修改后的模型时,我都会遇到EF Core跟踪问题的错误:
System.InvalidOperationException: The instance of entity type 'Product' cannot be
tracked because another instance with the key value '{ID: 2}' is already being
tracked. When attaching existing entities, ensure that only one entity instance
with a given key value is attached.
我认为这是由于“变异”记录会创建一个新的对象实例,而EF Core的跟踪系统不喜欢它,但我不确定最佳修复方式。有人有什么建议吗?还是我应该回到使用常规类而不是记录吗?
以下是重现问题的片段:
// Models/Product.cs
public record Product(int ID, string Name);
// Controllers/ProductController.cs
[HttpGet("test/{id}")]
public async Task<Product> ExampleControllerAction(int id, CancellationToken cancellationToken)
{
string newName = "test new name!!";
Product product = await db.Products.FindAsync(new object[] { id }, cancellationToken);
product = product with { Name = newName }; // Modify the model.
db.Update(product); // InvalidOperationException happens here.
await db.SaveChangesAsync(cancellationToken);
return product;
}
with
的评论,我完全忽略了那个逻辑。 - Silvermind