【问题标题】:Failed because another entity of the same type already has the same primary key value失败,因为同一类型的另一个实体已经具有相同的主键值
【发布时间】:2017-08-10 05:25:23
【问题描述】:

错误:

附加信息:附加类型为“Entities.Customer”的实体失败,因为同一类型的另一个实体已经具有相同的主键值。如果图中的任何实体具有冲突的键值,则在使用“附加”方法或将实体的状态设置为“未更改”或“已修改”时,可能会发生这种情况。这可能是因为某些实体是新实体并且尚未收到数据库生成的键值。在这种情况下,使用“Add”方法或“Added”实体来跟踪图表,然后将非新实体的状态设置为“未更改”或“已修改”。

我的代码:

public bool Update(TEntity entity)
{
        bool result = false;

        try
        {
            EntitySet.Attach(entity);

            Context.Entry<TEntity>(entity).State = EntityState.Modified;
            Context.SaveChanges();
            result = true;
        }
        catch (Exception)
        {
            throw;
        }

        return result;
}

我是这样工作的,我不知道,因为它不再工作了

【问题讨论】:

  • 您展示了一小段代码。目前尚不清楚EntitySet 的初始化位置或它的生命周期是什么。此错误通常表明上下文的生命周期过长。
  • 如果你真的想要一个答案,你将不得不付出更多的努力来提供关于 cmets 和答案的有意义的反馈。

标签: c# entity-framework


【解决方案1】:

尝试从数据库或本地上下文中获取实体,然后更新它。例如,在您的 catch 块中执行此操作。 这种情况下的 catch 块示例:

catch
{
    // get entity here
    // for example Context.Set<TEntity().Local.FirstOrDefault(selector); 
    //or .Find() instead of .FirstOrDefault()
    Context.Entry(entity).State = EntityState.Modified;
    Context.SaveChanges();
}

【讨论】:

    【解决方案2】:

    用 using 块试试这个方法:

    try
    {
        /* For avoiding "Attaching an entity of type 'Xxxxx' failed because another entity of 
        the same type already has the same primary key value." error use this method like this */
        using (var context = new Context.Entry<TEntity>())
        {
            context.Entry(entity).State = EntityState.Modified; // modified
            context.SaveChanges(); //Must be in using block
            result = true;
        }
    }
    

    希望这会有所帮助...

    【讨论】:

      猜你喜欢
      • 2015-01-08
      • 2014-07-18
      • 1970-01-01
      • 1970-01-01
      • 2017-05-13
      • 1970-01-01
      • 2014-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多