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.
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....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With