2016-03-08 64 views
0

我試圖從與其他表與外鍵共享關係的表中刪除記錄。因此,在我刪除任務記錄之前,我先刪除其他相關表中的記錄,如下面的代碼所示。從外鍵刪除記錄時從實體框架中的錯誤

public BusinessResult DeleteTask(int taskID) 
{ 
    Validator validator = new Validator(); 

    if (validator.NotZeroOrLower(taskID, TaskErrors.InvalidTaskID).IsValid) 
    { 
     DBTask dbTask = _TaskRepository.FindBy(task => task.ID == taskID, 
               task => task.WorkProcedureTasks).SingleOrDefault(); 


     if (validator.NullObject(dbTask, false, TaskErrors.InvalidTaskID).IsValid 
       && validator.Bool(dbTask.ClientWorkProcedureTasks.Count == 0, true, TaskErrors.TaskIsInUse).IsValid) 
     { 
      try 
      { 
       if (dbTask.WorkProcedureTasks.Count != 0) 
       { 
        List<int> workProcIDs = dbTask.WorkProcedureTasks.Select(w => w.WorkProcedureID).ToList(); 

        DeleteDependentRecords<DBWorkProcedureTask>(entity => entity.TaskID == taskID); 

        foreach (int workProcID in workProcIDs) 
        { 
         DBWorkProcedure dbWkproc = _WorkProcedureRepository.FindBy(proc => proc.ID == workProcID).First(); 

         dbWkproc.SubJobs.Clear(); 
         _WorkProcedureRepository.Delete(dbWkproc); 
        } 

        _WorkProcedureRepository.Save(); 
       } 

       ClearTasksByType(dbTask.ID); 
       _TaskRepository.Refresh(dbTask);       
       _TaskRepository.Delete(dbTask); 
       _TaskRepository.Save(); 
       dbTask. 
      } 
      catch (Exception e) 
      { 
       string err = e.Message.ToString(); 
      } 
     } 
    } 

    return validator.Result; 
}  

只要代碼點擊_TaskRepository.Save();崩潰與錯誤:

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable.

當我再次運行該刪除過程,它工作正常。 refresh()不起作用,所以我能做些什麼才能使其正常工作?

回答

0

你有很多很多,你是不是刪除它正確

dbWkproc.SubJobs.Clear(); 

更改爲

_context.SubJobs.RemoveRange(dbWkproc.SubJobs) 

或者,如果你沒有在上下文中則

_context.Set<SubJobsType>().RemoveRange(dbWkproc.SubJobs) 

原因子作業爲什麼它拋出的異常是,EF「認爲」你將連接到這個鏈接你的DBWork的表的連接刪除Procedure和SubJob類型,而不是刪除連接記錄,它嘗試在該記錄中將DbWorkProcedure設置爲null