Attaching an entity of type 'xxxx' failed because another entity of the same type already

Posted by Sheonarayan under Error and Solution on 5/15/2015 | Points: 10 | Views : 13255 | Status : [Administrator] | Replies : 0

Problem


I was getting following error while I was trying to access the object that I was about to modify in the Edit method to get the existing value of the field in the database.

Attaching an entity of type 'Model.ModelClass' 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.

I was writing below code to get the existing object based on primary key from the database.

var thisPost = db.HowtoPosts.Find(postId)


Solution


The solution of this problem is to use .AsNoTracking() method in the collection and then find the object using where clause.

var thisPost = db.HowtoPosts.AsNoTracking().Where(p => p.PostId == howtoPost.PostId).FirstOrDefault();

Hope this helps.

Thanks

Regards,
Sheo Narayan
http://www.dotnetfunda.com



Responses

(No response found.)

Login to post response