我有一個'EnterpriseEntity'和'TagsEntity',它們在名爲'EnterpriseTag'的表 中有多對多關係,這個關係表只存儲了EnterpriseID和TagID。需要幫助更新EF4中的多對多關係
我的問題是用EF4更新它。我的代碼如下:
//Delete old tags
foreach(var oldTag in e.Tags.ToList())
{
_enterpriseRepository.dbContext.DeleteObject(oldTag);
}
//now insert the new ones, this may have elements from old tag list
foreach(var newTag in newTags)
{
e.Tags.Add(newTag);
}
正如你可以看到newTags列表可能是因爲舊的標籤列表中的元素,但我不想在閒暇時通過檢查標記,標記。
但是,當我打電話.Savechanges()我得到以下異常:
添加與在已刪除狀態 不允許一個實體的關係。
UPDATE: 在我的原代碼,我有:
//This delete the Tag object, and i just want to delete the relation
_enterpriseRepository.dbContext.DeleteObject(oldTag);
正確的方法做到這一點:
//this just delete the relation, not the tag
e.Tags.Remove(oldTag);
您需要克隆舊標籤。或者另一種選擇是(1)保存你的第一輪刪除,(2)迭代你的'newTags'集合中的'_enterpriseRepository.dbContext.Detach(xxxxx)'實體並調用'xxxxx.MarkAsAdded'(如果你有自我追蹤的實體),(3)執行你的循環,調用'e.Tags.Add(newTag);'。 – Jaxidian