System.InvalidOperationException in EF core when trying to update

asp.net-core asp.net-web-api2 entity-framework-core repository-pattern

Question

Problem

I am creating a web app in asp.net core with ef core using with Repository pattern. Ii am trying to insert an entity it works fine when i trying to check whether it is already exist in db or then if yes than update the same entity in same api it gives me this error.

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.'

Image

enter image description here

code

insert 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");
}
1
0
8/17/2017 4:31:06 AM

Accepted Answer

The update process is

1- Retrieve the object which is consult in your code:

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

2- make change to the retrieval object (copy content from consultation to consult) you don't have it.

3- update the object consult

4- save change.

1
8/17/2017 5:00:39 AM

Popular Answer

Maybe try this for the line before SaveChanges().

_context.AddOrUpdate(entity);

This needs the System.Data.Entity.Migrations namespace.

Your question might already be answered here: Update Row if it Exists Else Insert Logic with Entity Framework



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow