删除数据的问题

时间:2014-07-15 15:04:56

标签: c# entity-framework

两个表格如下。当我删除任何用户时,只会删除用户,这对我来说没问题。当我删除任何薪水时,将删除与此记录相关的所有用户。我只想删除工资。

class Employee
{
    [Key]
    public int EmployeeId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    [Range(00000000000.00, 999999999999.00, ErrorMessage = "Amount must be between 00000000000.00 and 999999999999.00")]
    public decimal Phone { get; set; }
    public int SalaryId { get; set; }
    public virtual Salary Salary { get; set; }

}


    class Salary
{
    [Key]
    public int SalaryId { get; set; }
    public string Name { get; set; }
    [Range(0.01, 100000000.00, ErrorMessage = "Amount must be between 0.01 and 100000000.00")]
    public decimal Amount { get; set; }
}


private void DelEmp()
    {
        if (abort)
            return;
        else
        {
            int selectedRows = dgv1.Rows.GetRowCount(DataGridViewElementStates.Selected);
            for (int i = 0; i < selectedRows; ++i)
            {
                int id = Convert.ToInt32(dgv1.SelectedRows[i].Cells[0].Value);
                var emp = empSalDB.Employees.Single(e => e.EmployeeId == id);
                if (emp != null)
                {
                    empSalDB.Employees.Remove(emp);
                    empSalDB.SaveChanges();
                }
            }
        }
    }



private void DelSal()
    {
        if (abort)
            return;
        else
        {
            int selectedRows = dgv1.Rows.GetRowCount(DataGridViewElementStates.Selected);
            for (int i = 0; i < selectedRows; ++i)
            {
                int id = Convert.ToInt32(dgv1.SelectedRows[i].Cells[0].Value);
                var sal = empSalDB.Salaries.Single(s => s.SalaryId == id);
                if (sal != null)
                {
                    empSalDB.Salaries.Remove(sal);
                    empSalDB.SaveChanges();
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

您需要将Employee的SalaryId标记为可为空。如果它不可为空,那么删除工资时会发生什么?相关的Employee的SalaryId不能设置为已删除的Salary的Id,因为它不存在但您不能将Id保留为null。薪水对员工来说是可选的,因此通过允许它为空来反映。

public class Employee
{
    ...
    public int? SalaryId { get; set; }
}

或者,您可以使用Fluent API的WillCascadeOnDelete(true)打开CascadeDelete。