System.InvalidOperationException 尝试更新时在 EF 核心中

System.InvalidOperationException in EF core when trying to update

问题

我正在 asp.net 核心中使用 ef 核心创建一个 Web 应用程序,并使用存储库模式。我正在尝试插入一个实体,当我尝试检查它是否已经存在于数据库中时,它工作正常,或者如果是,则在相同的 api 中更新相同的实体,它给了我这个错误。

System.InvalidOperationException: 'The instance of entity type 'Consultation' cannot be tracked because another instance of this type with the same key is already being tracked. When adding new entities, for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type). If you are explicitly setting key values for new entities, ensure they do not collide with existing entities or temporary values generated for other new entities. When attaching existing entities, ensure that only one entity instance with a given key value is attached to the context.'

图片

代码

插入api

[HttpPost]
public ApiResponse InsertConsultation([FromBody] Consultation consultation)
{
    if (!ModelState.IsValid)
    {
        return new ApiResponse(StatusCodes.Status400BadRequest, error: "error");
    }

    var consult = _consultationService.GetConsultationById(consultation.Id);

    if (consult !=null)
    {
        _consultationService.UpdateConsultation(consultation);
        return new ApiResponse(StatusCodes.Status200OK, success: "isSuccess");
    }

    _consultationService.InsertConsultation(consultation);
    return new ApiResponse(StatusCodes.Status201Created, success: "isSuccess");
}

也许在 SaveChanges() 之前的行中尝试这个。

_context.AddOrUpdate(entity);

这需要 System.Data.Entity.Migrations 命名空间。

您的问题可能已在此处得到解答: Update Row if it Exists Else Insert Logic with Entity Framework

更新过程为

1- 检索代码中参考的对象:

var consult = _consultationService.GetConsultationById(consultation.Id);

2-修改检索对象(复制咨询内容进行咨询)你没有

3-更新对象consult

4- 保存更改。