积极答复者
Entity Framework一对多对象 批量删除子对象

问题
-
var standardChemicalElement = this.GetById(id); standardChemicalElement.ChemicalElementItems.Clear(); this.DataContext.StandardChemicalElement.Attach(standardChemicalElement); this.DataContext.Entry(standardChemicalElement).State = EntityState.Modified; DataContext.Commit();
以上代码报错
其他信息: 操作失败: 无法更改关系,因为一个或多个外键属性不可以为 null。对关系作出更改后,会将相关的外键属性设置为 null 值。如果外键不支持 null 值,则必须定义新的关系,必须向外键属性分配另一个非 null 值,或必须删除无关的对象。
var standardChemicalElement = this.GetById(id); foreach (var item in standardChemicalElement.ChemicalElementItems.ToList()) { this.DataContext.StandardChemicalElementItem.Remove(item); this.DataContext.StandardChemicalElementItem.Attach(item); this.DataContext.Entry(item).State = EntityState.Modified; } DataContext.Commit();
改为以上代码后无报错,但数据并未删除
如何才能做到批量删除子对象?
答案
-
var standardChemicalElement = this.GetById(id); foreach (var item in standardChemicalElement.ChemicalElementItems.ToList()) { this.DataContext.StandardChemicalElementItem.Remove(item); this.DataContext.StandardChemicalElementItem.Attach(item); this.DataContext.Entry(item).State = <em>EntityState.Deleted;</em> } DataContext.Commit();
更改当前实体状态为 EntityState.Deleted 即可- 已标记为答案 bombw 2011年8月31日 1:56
全部回复
-
請問你是使用LINQ TO SQL嗎?建議可以參考MSDN上的範例,有詳盡的說明。
以下節錄自演练:操作数据 (C#) (LINQ to SQL):
// Access the first element in the Orders collection. Order ord0 = existingCust.Orders[0]; // Access the first element in the OrderDetails collection. OrderDetail detail0 = ord0.OrderDetails[0]; // Display the order to be deleted. Console.WriteLine ("The Order Detail to be deleted is: OrderID = {0}, ProductID = {1}", detail0.OrderID, detail0.ProductID); // Mark the Order Detail row for deletion from the database. db.OrderDetails.DeleteOnSubmit(detail0);
以上說明若有錯誤請指教,謝謝。
http://www.dotblogs.com.tw/terrychuang/ -
var standardChemicalElement = this.GetById(id); foreach (var item in standardChemicalElement.ChemicalElementItems.ToList()) { this.DataContext.StandardChemicalElementItem.Remove(item); this.DataContext.StandardChemicalElementItem.Attach(item); this.DataContext.Entry(item).State = <em>EntityState.Deleted;</em> } DataContext.Commit();
更改当前实体状态为 EntityState.Deleted 即可- 已标记为答案 bombw 2011年8月31日 1:56