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()不起作用,所以我能做些什麼才能使其正常工作?