我正在使用Entity Framework 5和MVC 4代码的第一种方法。我对这两个都很新,所以我可能做了一个简单的错误,我试图从数据库中删除多对多的关系。我可以添加关系很好,但当我想删除它时,我得到一个错误。
我必须与多对多的关系表。我有Employee类和演绎类:
通过ICollection链接到Deduction类的Employee类:
public class Employee
{
public int EmployeeID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int PhoneNumber { get; set; }
public int CellNumber { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public int PostalCode { get; set; }
public string BankName { get; set; }
public int BankAccountNumber { get; set; }
public string PayInterval { get; set; }
public double NormalRate { get; set; }
public double OvertimeRate { get; set; }
public double SetHours { get; set; }
public DateTime DateOfEmployment { get; set; }
public DateTime LastPaymentRecieved { get; set; }
public string Active { get; set; }
public int JobID { get; set; }
public ICollection<Holiday> holiday { get; set; }
public ICollection<Bonus> bonus { get; set; }
public ICollection<Absent> absent { get; set; }
public Job Job { get; set; }
public ICollection<Deduction> Deductions { get; set; }
public ICollection<HoursWorked> HoursWorke { get; set; }
public ICollection<Payroll> Payrolls { get; set; }
}
通过ICollection链接到Employee类的扣除类:
public class Deduction
{
public int DeductionID { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public double Amount { get; set; }
public ICollection<Employee> Employee { get; set; }
public ICollection<Payroll> Payroll { get; set; }
}
以下是我目前删除的代码:
public void RemoveEmployeeDeduction(int empID, int dedID)
{
var employee = db.Employee.FirstOrDefault(x => x.EmployeeID == empID);
var ded = db.Deduction.FirstOrDefault(x => x.DeductionID == dedID);
employee.Deductions.Remove(ded);
db.SaveChanges();
}
我确实检查了员工和我要删除的扣除是否正确获取。我注意到在employee.Deductions.Remove(ded),扣减为空。 这是错误:
我也尝试了堆栈溢出的多个答案,但似乎没有工作,所以也许我的代码的一个例子可以帮助我。
提前致谢。
修改
我已通过添加以下内容解决了此错误: 问题是我在检索员工时没有包含扣减。它现在按预期工作。
public void RemoveEmployeeDeduction(int empID, int dedID)
{
var employee = db.Employee.Include("Deductions").FirstOrDefault(x => x.EmployeeID == empID);
var ded = db.Deduction.FirstOrDefault(x => x.DeductionID == dedID);
employee.Deductions.Remove(ded);
db.SaveChanges();
}