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)