Updating existing data in EF 6 throws exception - “…entity of the same type already has the same primary key value.”

前端 未结 4 1728
眼角桃花
眼角桃花 2020-12-29 13:39

I am trying to update a record using Entity Framework 6, code-first, no fluent mapping or a tool like Automapper.

The entity(Employee) has other composi

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-29 14:19

    EF already includes a way to map properties without resorting to Automapper, assuming you do not have navigation properties to update:

    public bool UpdateEmployee(Employee employee)
        {
            var entity = _dbContext.Employees.Where(c => c.Id == employee.Id).AsQueryable().FirstOrDefault();
            if (entity == null)
            {
                _dbContext.Employees.Add(employee);
            }
            else
            {
                _dbContext.Entry(entity).CurrentValues.SetValues(employee);              
            }
    
            return _dbContext.SaveChanges() > 0;
    
        }
    

    This usually generates a better SQL statement since it will only update the properties that have changed.

    If you still want to use the original method, you'll get rid of entity from the context, either using AsNoTracking (not sure why it didn't update in your case, it should have no effect, so the problem might be something else) or as modifying your query to prevent it from materializing the entity in the first place, using something like bool exists = dbContext.Employees.Any(c => c.Id == employee.Id) for example.

提交回复
热议问题