C# – EF, Automapper exception, “Attaching an entity of type … failed because another entity of the same type already has the same primary key value”

automappercentity-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;
        context.SaveChanges();

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?

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