0

I am facing one issue while updating entity with some of the fields updating from original entity. Code is like below

 public int SaveUser(UserDetail objUserDet)
    {
     DBEntities context = new DBEntities();
     UserDetail userDetail = (from u in context.UserDetails.Where(u => u.UserDetID == objUserDet.UserDetID)
                                         select u).Single();
     objUserDet.UserId = userDetail.UserId;
     //context.UserDetails.ApplyCurrentValues(objUserDet); //For ObjectContext works fine.
     context.UserDetails.Attach(objUserDet);
     context.Entry(objUserDet).State = EntityState.Modified;
     context.SaveChanges();
    }

But it gives me an error like

Attaching an entity of type failed because another entity of the same type already has the same primary key value.

How to update one entity with another is present with same primary key.

Rajaram Shelar
  • 7,537
  • 24
  • 66
  • 107
  • this is not correct use of attach method, I think you meant to use update method. – tmg Mar 26 '15 at 15:55
  • Please have a look at my answer on [ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value](http://stackoverflow.com/questions/23201907/asp-net-mvc-attaching-an-entity-of-type-modelname-failed-because-another-ent/39557606#39557606). – Murat Yıldız Sep 18 '16 at 12:27

1 Answers1

1

I'm 99% sure that the error is due to having two attached objects in the in-memory context with the same primary key. So, you should either:

  1. NOT select userDetail, or
  2. NOT attach objUserDet and transfer the changed values to the userDetail object instead.

You might also be able to detach the userDetail object before SaveChanges.

samiz
  • 1,043
  • 1
  • 13
  • 21