如果你做這樣的事情:
User u;
using (Entities ent = new Entities())
{
u = ent.Users.Single(a => a.ID == 123);
}
using (Entities ent2 = new Entities())
{
//loading the same user
User user2 = ent2.Users.Single(a => a.ID == 123);
//trying to attach the same object with the same key
ent2.Attach(u);
}
那麼你會得到這個錯誤(我沒有測試此代碼)。
編輯:的解決方案之一是改變對象的狀態:
ent2.Attach(u);
ent2.ObjectStateManager.ChangeObjectState(u, EntityState.Modified);
另一種解決方案是檢查實體已經附:
ObjectStateEntry state = null;
if(!ent2.ObjectStateManager.TryGetObjectStateEntry(((IEntityWithKey)u).EntityKey, out state))
{
ent2.Attach(u);
}
你從哪裏得到這個附屬實體?從相同的上下文? – Alex
不,來自另一個環境。我總是在使用句子中使用新的語境。 –
我認爲在另一個環境中已經存在相同的實體(使用相同的鍵)。 – Alex