在EF 6更新现有数据抛出异常 - " ......同类型的实体已经拥有相同的主键值" [英] Updating existing data in EF 6 throws exception - "...entity of the same type already has the same primary key value."

查看:1406
本文介绍了在EF 6更新现有数据抛出异常 - " ......同类型的实体已经拥有相同的主键值"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图更新使用实体框架6,代码为先,不流利的映射或类似Automapper工具的记录。

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

实体(员工)的>它像 Addreess 处

The entity(Employee) has other composite properties associated with it like Addreess(collection), Department

这也从一个名为用户

另存方法如下,与 _dbContext 作为 DbConext 实施

The save method is as follows, with _dbContext being the DbConext 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 the error:

附加类型的实体失败,因为在同一
型的另一个实体已经有相同的主键值。发生这种情况时,使用'连接'方法或实体的状态设置为

'不变'或'修改',如果图中的任何实体具有
冲突的键值。这可能是因为一些实体是新的,
尚未收到数据库生成的键值。在这种情况下,可以用
中的添加方法或添加实体状态跟踪图形和
然后设置非新的实体,以'不变'或'修改'作为$ B $状态; b相应的

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.

我曾尝试以下内容:


  1. 设置为 EntityState.Modified 之前附加

  2. 添加 AsNoTracking()上查询,如果该对象存在(无异常,但不更新DB) - http://stackoverflow.com/a/23228001/ 919426

  3. 使用节能基实体 _dbContext.Users 而不是雇员实体 - 的http://stackoverflow.com/a/25575634/919426

  1. Attaching before setting to EntityState.Modified
  2. Adding AsNoTracking() on querying if the object exists(No exception but DB is not updated) - http://stackoverflow.com/a/23228001/919426
  3. Saving using the base entity _dbContext.Users instead of the Employee entity - http://stackoverflow.com/a/25575634/919426

这是现在的工作对我来说都不是。

None of which is working for me now.

什么可能我已经得到了错误的其中一些解决方案,不要在我的情况下工作?

What could I have gotten wrong for some of those solutions not to work in my situation?

推荐答案

EF已经包含了一种不诉诸Automapper属性映射,假设你没有导航属性以更新:

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;

    }

这通常会产生更好的SQL语句,因为它只会更新已更改的属性。

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

如果你还是想用原来的方法,你会摆脱实体从上下文,或者使用AsNoTracking(不知道为什么它没有你的情况下更新,应该没有效果,所以这个问题可能是别的东西)或修改您的查询,以防止它在第一物化实体的地方,使用类似布尔存在= dbContext.Employees.Any(C => c.Id == employee.Id)。例如:

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.

这篇关于在EF 6更新现有数据抛出异常 - &QUOT; ......同类型的实体已经拥有相同的主键值&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆