2011-08-16 76 views
0

我想更新整個實體對象與實體框架中的數據庫中的關係,並沒有成功。在實體框架中有更新對象有關係

我試圖做這樣的事情:

var objectToUpdate = DAL.GetProduct(id); 
// then I have collection of Comments related to this product. 
// and I want to update th whole collection 
objectToUpdate.Comments.Clear(); 
foreach(var newComment in comments){ 
    objectToUpdate.Comments.Add(newComment); 
} 

我所得到的數據庫是所有與我的產品評論的重複。 請建議如何正確更新相關實體。

謝謝。

回答

0

如果您想更新objectToUpdate與數據庫中已存在的註釋集合之間的關係,您需要將註釋附加到上下文,然後將其添加到objectToUpdateComments集合中。否則EF將在數據庫中創建新的評論行:

var objectToUpdate = DAL.GetProduct(id); 
objectToUpdate.Comments.Clear(); 
foreach(var newComment in comments) 
{ 
    context.Comments.Attach(newComment); 
    objectToUpdate.Comments.Add(newComment); 
}