从MVC服务中删除项目时出错

时间:2015-03-25 12:03:30

标签: c# asp.net-mvc entity-framework model-view-controller

点击删除后我收到此错误:

 try
        {
            var crews = await GetCrewsAttached(id);
            var assetbookings = await _assetBooking.Get(id);
            var parts = await GetParts("LTD", id, false);
            //Checks if records exist in assetbookings and the employee not attached to any crew and doesnt have any parts associated to the employee
            if (assetbookings == null && (crews.Count() == 0 || crews == null) && (parts == null || parts.ToList().Count() == 0))
            {
                var employee = await _employeeRepository.Get(
                  e => e.EmployeeID == id,
                  new List<Expression<Func<gblEmployee, object>>>() {
                    (e => e.Address),
                    (e => e.EmployeeTraining.Select(t=>t.Training)),
                    (e => e.EmployeeWorkSchedule)
                });

                if (employee != null && employee.IsSupervisor != true)
                {
                    foreach (var training in employee.EmployeeTraining)
                    {
                        _employeeTrainingRepository.Delete(training);
                    }
                    await _employeeTrainingRepository.Commit();


                    if (employee.Address != null)
                    {
                        _addressRepository.Delete(employee.Address);
                        await _addressRepository.Commit();
                    }
                    _employeeRepository.Delete(employee);
                    await _employeeRepository.Commit();


                }
            }
        }
        catch (Exception ex)
        {
            throw new NexgenException(ex);
        }

我在await _employeeRepository.Commit();

收到错误

任何解决方法? 错误是操作失败:无法更改关系,因为一个或多个外键属性不可为空。当对关系进行更改时,相关的外键属性将设置为空值。如果外键不支持空值,则必须定义新关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象

1 个答案:

答案 0 :(得分:0)

尝试在提交之前调用.SaveChanges。您还可以创建捕获DbEntityValidationException的catch块,以便检查缺失值