Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework the delete statement conflicted with the reference constraint

I have two tables Employee (n) and Store (1), which have n:1 relationship.

Employee has foreign key idStore which is primary key from Store.

Here is how I try to delete a row from Employee:

public void deleteEmployee(int idEmployee)
{
   MyEntities pe = new MyEntities();
   try
   {
      var firstQuery = from e in pe.Employees
                       where e.idEmployee == idEmployee
                       select e;
      string findIdStore = firstQuery.First().StoreReference.EntityKey.EntityKeyValues[0].Value.ToString();
      int idStore = Int32.Parse(findIdStore);
      Store r = pe.Stores.First(c => c.idStore == idStore);
      r.Employees.Remove(firstQuery.First());
      pe.DeleteObject(firstQuery.First());
      pe.SaveChanges();
   }
   catch (Exception ex)
   {
      return;
   }
}

And still, I get error that the delete statement conflicted with the reference constraint.

The complete error is here:

The DELETE statement conflicted with the REFERENCE constraint "FK_Bill_Employee". The conflict occurred in database "myDatabase", table "dbo.Bill", column 'idEmployeeMember'.
The statement has been terminated.

like image 371
petko_stankoski Avatar asked Nov 13 '22 12:11

petko_stankoski


1 Answers

Can't you just find and delete the employee??

public void deleteEmployee(int idEmployee)
{
   using(MyEntities pe = new MyEntities())
   {
      var emmployeeToDelete = pe.Employees.FirstOrDefault(e => e.idEmployee == idEmployee);

      if(employeeToDelete != null)
      {
          pe.DeleteObject(employeeToDelete);
          pe.SaveChanges();
      }
   }
}

I don't think you need to do anything more than this, really.....

Next time when you load this particular store the employee belonged to, that employee will no longer be in the store's collection of employees - without doing any messy manual deletes or anything....

like image 143
marc_s Avatar answered Jan 07 '23 00:01

marc_s