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

c# entity-framework entity-framework-6

Question

Using Entity Framework 6 and either a tool like Automapper or code-first, no fluent mapping, I'm attempting to change a record.

The thing(Employee ) also has additional composite characteristics, such asAddreess (collection), Department

Additionally, it comes from a base known asUser

The save approach is as follows:_dbContext owing toDbConext implementation

        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(employee).State = EntityState.Modified; // <- Exception raised here
                _dbContext.Employees.Attach(employee);

            }

            return _dbContext.SaveChanges() > 0;

        }

I keep getting this error:

Attaching an entity of type 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.

I've tried these things:

  1. affixing before startingEntityState.Modified
  2. Adding AsNoTracking() on asking whether the thing is present (No exception but DB is not updated) - zzzz-57-zz
  3. Using the base entity for saving_dbContext.Users the Employee entity - https://stackoverflow.com/a/25575634/919426

None of which are now working for me.

What could I have done differently for some of those solutions to not work for me?

1
8
5/23/2017 12:25:36 PM

Accepted Answer

Without using Automapper, EF already has a means to map properties: Considering that you lack 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;

    }

Because it just updates the attributes that have changed, this typically results in a better SQL statement.

If you still want to employ the original technique, removeentity the context, either by altering your query to stop it from materializing the entity in the first place, using something like, or by using AsNoTracking (not sure why it didn't update in your case; it should have no effect, so the problem might be something else).bool exists = dbContext.Employees.Any(c => c.Id == employee.Id) for instance.

23
6/7/2015 12:09:38 PM

Popular Answer

ZZZ_tmp


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