I have an entity which I need to save twice. The first time is to set the ID. This ID needs to be filled to calculate a signature and that signature is stored back to the entity.
See the following code:
var newEntity = new MyEntity
{
\\ set values
};
using (var db = MyContainer.CreateContainer())
{
db.MyEntity.Add(newEntity);
// Call SaveChanges() to set the ID.
db.SaveChanges();
// I need to do some calculation on the entity
myEntity.Signature = CalculateSignature(myEntity);
db.SaveChanges(); // <--- This causes the exception
}
This piece of code causes an InvalidOperationException, namely The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.
I don't understand, am I not allowed to save the same entity twice? How would I go about achieving this?