I am trying to delete a Record from Employee table based on EmpId which is the primary key (EmpId is also a foreign key for table Salary) using LINQ in asp.net web Api. But I am getting an error which is: SQL Exception:
The DELETE statement conflicted with the REFERENCE constraint "FK__Salary__EmpId__3B75D760". The conflict occurred in database "CRUDWithLINQ", table "db. Salary", column ‘EmpId.
Please Help me out.
public bool DeleteEmployee(int id)
{
var employee = (from Employee
in _context.Employees
where Employee.EmpId == id
select Employee).FirstOrDefault();
if (employee == null)
{
return false;
}
var salaries = (from Salary in _context.Salaries//Salaries is entity for Salary
where Salary.EmpId == id
select Salary).FirstOrDefault();
var salaries = _context.Salaries.Where(s => s.EmpId == id);
_context.Salaries.RemoveRange(salaries);
_context.Employees.Remove(employee);
_context.SaveChanges();
return true;
}
2
Answers
you need to ensure that the related salary records are deleted before you attempt to delete the employee record.
The error means that you cannot delete the Salaries because they are referenced by another table in your database.
See Stack Overflow:I got error "The DELETE statement conflicted with the REFERENCE constraint"