EF, Automapper exception, "Attaching an entity of type ... failed because another entity of the same type already has the same primary key value"

automapper c# entity-framework


I am refactoring some code using automapper, see below with the old code commented out.

var propertyInUse = context.Properties.FirstOrDefault(j => j.ID != src.PropertyId && j.UPRN.ToLower() == src.UPRN.ToLower() && j.ContractId == src.ContractId);

if (propertyInUse == null)
    var property = context.Properties.FirstOrDefault(j => j.ID == src.PropertyId);

    if (property != null)
        if (src.PropertyTypeId == 0)
            src.PropertyTypeId = null;

        src.Created = property.Created;
        src.CreatedBy = property.CreatedBy;
        src.ContractId = property.ContractId;

        Mapper.CreateMap<Job, Property>();
        property = Mapper.Map<Property>(src);
        //property.PropertyNo = src.PropertyNo;
        //property.BlockName = src.BlockName;
        //property.StreetName = src.StreetName;
        //property.AddressLine2 = src.AddressLine2;
        //property.AddressLine3 = src.AddressLine3;
        //property.AddressLine4 = src.AddressLine4;
        //property.Postcode = src.Postcode;
        //property.Latitude = src.Latitude;
        //property.Longitude = src.Longitude;
        //property.BlockUPRN = src.BlockUPRN;
        //property.Comments = src.Comments;
        //property.NumberOfBathrooms = src.NumberOfBathrooms;
        //property.NumberOfBedrooms = src.NumberOfBedrooms;
        //property.NumberOfKitchens = src.NumberOfKitchens;
        //property.LastModifiedby = src.LastModifiedby;
        property.LastModified = DateTime.Now;
        context.Entry(property).State = EntityState.Modified;
        success = true;

EDIT: Please note that property object is set from the base so that the proposed duplicate question does not apply.

When the state is set to modified, I get the following exception;

Attaching an entity of type 'M.Survey.ServiceLayer.Model.Property' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

What is causing this and how do I fix it?

8/5/2015 1:08:11 PM

Accepted Answer

Have you tried mapping to the existing object instead?

Mapper.Map(src, property);

That business about entity state junk rarely works out right. Instead, map the value from the DTO into the entity returned by EF.

8/5/2015 1:44:13 PM

Popular Answer

Looking at the error message: Attaching failed because another entity of the same type has already the same primary key value.

We faced this problem aswell in the past:

  1. We loaded an object A that has childobject B within a dbcontext and then used these objects on the GUI
  2. When permitting a post from the GUI, we loaded another object B' (having same PK as B) with another database context, this object was only used to verify some changes in parameters.
  3. Then we wanted to save the object A with childobject B towards the database by attaching it to the dbcontext, but then the error occured.

The error occured because, aside object B' there was already an object B with the same PK, originated from another database context.

We solved this problem by avoiding duplicate keys of same object type within one dbcontext by:

  1. Refetching object A and his child object B and then setting all properties from GUImodels and then flushing it towards the databse.
  2. We no longer: attached the GUImodels (Object A and B from previous dbcontext)
  3. We no longer fetched object B separately.

In your code: Can it be that object property is already loaded as a childobject from object src and then automatically mappped to object property and thus added to the context which then will notify an objecttype with same pk ?

Here I found a similar post

Related Questions


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