The delete statement in Entity Framework clashed with the reference restriction.

entity-framework

Question

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.

1
5
8/15/2015 5:28:31 PM

Accepted Answer

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....

1
12/26/2011 4:35:01 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow