简体   繁体   中英

Error from Entity Framework when deleting records from table with foreign key

I'm trying to remove a record from a table which has shared relationships with other tables with a Foreign Key. So before I remove the task record I remove the records from other related tables first as in the code below.

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;
}       

As soon as the code hits _TaskRepository.Save(); it crashes with the error:

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

When I run the delete process again it works fine. The refresh() isn't working so what can I do to make this work properly?

You have many to many and you are not deleting it properly

dbWkproc.SubJobs.Clear();

Change this to

_context.SubJobs.RemoveRange(dbWkproc.SubJobs)

Or if you dont have subjobs in context then

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

Reason why it throw exception is that EF "think" that you are removing connection to this table which links your DBWorkProcedure and SubJob type, and istead of remove connection record it try to set DbWorkProcedure to null in that record

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM