0

I found a bug for my Employee edition page, where I simply am able to change information about a selected employee (name, login, password etc.)

_service.Edit(objToEdit)

Sends me to the following for edition:

public bool Edit(Employee objEmployee)
{            
    if (!Validate(objEmployee))
        return false;
    try
    {
        _repository.Edit(objEmployee);
    }
    catch
    {
        return false;
    }
    return true;
}

That finally goes to the following to save the changes :

public Employee Edit(Employee objEmployee) 
{
     var Original = Get(objEmployee.Login);
     if (Original != null)
     {
         var attachedEmp = _entities.Entry(Original);
         attachedEmp.CurrentValues.SetValues(objEmployee);
     }
     else
     {
         _entities.Employees.Add(objEmployee);
     }
     _entities.SaveChanges();
     return objEmployee;
 }

But once I reach _entities.SaveChanges() I get the following error :

The UPDATE statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_EmployeeEmployee2". The conflict occurred in database "CRAV34", table "dbo.Employee", column 'Login'. The statement has been terminated.

I looked it up but couldn't find anything that truly helped me. I have recently updated my database with new employees, edition works on old ones but seems to have this error on new ones.

Any help would be greatly appreciated !

1 Answers1

0

By what I can see from the provided details seems like you have a FK constraint from table Employee to table Employee on column Login. When you try to change the value of the Login column (in the Edit method), you effectively violate the constraint, so won't allow you to.

To fix this, drop that constraint.

If you need a lookup table for the Login column, create a separate table.

I can't think of a good reason to justify using a "reflective" FK. Maybe there are, but this doesn't seem to be the case.

Edit: How to drop constraint: right-click it and there'll probably be a delete/drop option (assuming you're using SQL Server).

enter image description here

You can also use SQL code (enter link description here):

ALTER TABLE <schema_name, sysname, dbo>.<table_name, sysname, table_name>
   DROP CONSTRAINT <default_constraint_name, sysname, default_constraint_name>
GO
Community
  • 1
  • 1
Ricardo Rodrigues
  • 2,198
  • 2
  • 18
  • 22