我有一个需要保存两次的实体。第一次是设置ID。需要填写此 ID 以计算签名并将该签名存储回实体。
请参阅以下代码:
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
}
这段代码会导致 InvalidOperationException,即The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.
我不明白,我不允许我两次保存同一个实体吗?我将如何实现这一目标?