Update record ... except one field

Mar 14, 2015 at 9:36 AM
Hello,

I have an entity "Employee" with some properties : FirstName, LastName, Login and Password. When I get an employee, I set in the result the Password property to blank to avoid send password to the client. The login is unique.

When I update this employee, the value are coming from the web client, the Password is empty, then first I get the Password for this employee set the Password property of the entity (to avoid to have a blank password in the database) to save and I do an update

When I do this, no problem (but the Password is set to blank)
private void Update(Employee employee)
{
    _unitOfWorkAsync.BeginTransaction();
    
    _repoEmployee.Update(employee);

    _unitOfWorkAsync.SaveChanges();
    _unitOfWorkAsync.Commit();
}
To avoid set a blank Password, I do this :
private void Update(Employee employee)
{
    var password = _repoEmployee.GetById(employee.Id).Password;
    
    _unitOfWorkAsync.BeginTransaction();
    
    employee.Password = password;
    _repoEmployee.Update(employee);

    _unitOfWorkAsync.SaveChanges();
    _unitOfWorkAsync.Commit();
}
I get this exception on the Update line :
Attaching an entity of type 'Pme.Entities.Employee' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

Could you help me ?

Thanks,
Coordinator
May 12, 2015 at 5:39 PM
You have two employees with the same Primary Key in the Context. Update all the properties
private void Update(Employee employee)
{
    var e = _repoEmployee.GetById(employee.Id);
    
    _unitOfWorkAsync.BeginTransaction();
    
    e.FirstName = employee.FirstName;
    e.LastName = employee.LastName;ZZ
    _repoEmployee.Update(e);

    _unitOfWorkAsync.SaveChanges();
    _unitOfWorkAsync.Commit();
}
Marked as answer by lelong37 on 5/12/2015 at 10:39 AM