0

I am trying to create a new instance of my domain model, that may be added or updated into the database. The idea is to perform some validations and check whether this entity will give origin to an update, or a new record in the db. The code below depicts what I am doing:

DbContext db = new DbContext();
MyEntity newEntity = new MyEntity();
newEntity.SomeField = ""; //some changes in the entity
...


MyEntity oldEntity = db.MyEntity.Find(someId);
if(oldEntity == null)
{
    db.MyEntity.Add(newEntity);
    db.SaveChanges();
}
else 
{
    newEntity.Id = oldEntity.Id; //giving the Id of the old entity, in order to update
    db.MyEntity.Attach(newEntity); //ERROR
    db.Entry(newEntity).State = EntityState.Modified;
    db.SaveChanges();
}

If I try to add, there aren't any problems, but if I try to update it, I get the following error message:

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

What am I missing here? How can I update that newEntity in the database? (if it is possible at all, given these conditions)

Manuel Reis
  • 574
  • 8
  • 29
  • 2
    You can't attach an entity onto an existing entity. You'd have to `Detach` the existing entity first. Try if this works and if it does, I'll post this as an answer (as this most probably is a good answer). – Wiktor Zychla Aug 27 '15 at 11:22
  • Yup, doing `db.Entry(oldEntity).State = EntityState.Detached;` worked for me. You can post it as an answer, I will mark it as accepted. Thanks! – Manuel Reis Aug 27 '15 at 11:30
  • @Jan'splite'Kondelík Yeah, I found pretty quickly that the `Detach` method does not exist... :) – Manuel Reis Aug 27 '15 at 11:32
  • You might 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:31

1 Answers1

1


You can try do something like this:

 private void Save(User newEntity,int someId)
    {
        InteractionsDBContext db = new InteractionsDBContext();            


        EntityFramework.User oldEntity = db.Users.Find(someId);
        if (oldEntity == null)
        {
            db.Users.Add(newEntity);
            db.SaveChanges();
        }
        else
        {                
            newEntity.UserId = oldEntity.UserId; //giving the Id of the old entity, in order to update
            db.Entry(oldEntity).State = EntityState.Detached;
            db.Users.Attach(newEntity); 
            db.Entry(newEntity).State = EntityState.Modified;
            db.SaveChanges();
        }
    }
Manuel Reis
  • 574
  • 8
  • 29