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


i refactoring code using automapper, see below 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 property object set base proposed duplicate question not apply.

when state set modified, following exception;

attaching entity of type 'm.survey.servicelayer.model.property' failed because entity of same type has same primary key value. can happen when using 'attach' method or setting state of entity 'unchanged' or 'modified' if entities in graph have conflicting key values. may because entities new , have not yet received database-generated key values. in case use 'add' method or 'added' entity state track graph , set state of non-new entities 'unchanged' or 'modified' appropriate.

what causing , how fix it?

have tried mapping existing object instead?

mapper.map(src, property); 

that business entity state junk works out right. instead, map value dto entity returned ef.


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -