删除记录以及子记录

问题描述:

我有一个提交控制器与其他几个表有一对多的关系。以下是我的型号:删除记录以及子记录

public partial class Submission 
{ 
    public Submission() 
    { 
     this.WorkorderLogs = new HashSet<WorkorderLog>(); 
    } 

    public int Id { get; set; } 
    public int WorkOrderId { get; set; } 
    public int PartStagingId { get; set; } 
    public System.DateTime SubmissionDate { get; set; } 

    public virtual PartStaging PartStaging { get; set; } 
    public virtual WorkOrder WorkOrder { get; set; } 
    public virtual ICollection<WorkorderLog> WorkorderLogs { get; set; } 
} 

我希望应用程序在删除提交记录时删除所有子记录。下面是我的删除方法:

[HttpPost, ActionName("Delete")] 
[ValidateAntiForgeryToken] 
public ActionResult DeleteConfirmed(int id) 
{ 
    Submission submission = db.Submissions.Find(id); 

    foreach (var w in submission.WorkorderLogs) 
    { 
     submission.WorkorderLogs.Remove(w); 
    } 

    db.Submissions.Remove(submission); 
    db.SaveChanges(); 

    return RedirectToAction("Index"); 
} 

这给了我在foreach循环的第一次迭代后的错误。以下是我得到的错误:

Exception Details: System.InvalidOperationException: Collection was modified; enumeration operation may not execute. 

如何在这种情况下删除子记录?

+0

参见[这里](http://stackoverflow.com/questions/16654828/how-to-remove柴尔德一到多的相关-记录功能于EF-代码优先数据库)。您也可以配置级联删除,而不是先删除所有子级。见[这里](http://stackoverflow.com/questions/5614485/deleting-multiple-records-for-a-related-table),和[这里](http://stackoverflow.com/questions/5448702/cascading -deletes-with-entity-framework-related-entities-deleted-by-ef),... – Jasen

+0

这与儿童相关记录无关。如果你不使用EF,你将会遇到同样的问题。你正在修改一个集合,而你正在迭代它。这是不允许的。你需要使用一个for循环,然后向后移动该集合中的项目,或者如果可能,只需从集合中执行RemoveAll! –

我不启用级联删除级联,但我修改了foreach循环和它的作品

foreach (var w in db.WorkorderLogs.Where(x => x.SubmissionId == submission.Id)) 
{ 
    db.WorkorderLogs.Remove(w); 
}