如何在EFCore中使用C#9记录?

c#

c#-9.0

我正在使用 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;
}

回答

如果您关闭 EF 更改跟踪,它应该按书面方式工作。尝试添加AsNoTracking()到原始 db 调用中。


回答

来自官方文档

Entity Framework Core 依赖于引用相等性以确保它仅使用实体类型的一个实例来表示概念上的一个实体。因此,记录类型不适合在 Entity Framework Core 中用作实体类型。


以上是如何在EFCore中使用C#9记录?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>