无法保存,因为“同一类型的另一个实体已经具有相同的主键值” [英] Unable to save because of 'another entity of the same type already has the same primary key value'

查看:880
本文介绍了无法保存,因为“同一类型的另一个实体已经具有相同的主键值”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个控制器操作:

[HttpGet]
[Route("api/person/test/{id}")]
public IHttpActionResult Test(Guid id)
{
    var person = this.PersonManager.Get(id);

    person.Lastname = "Jameson";

    this.PersonManager.Save(person);

    return Ok(true);
}

此保存方法下方深入调用:

Deep underneath this save method is called:

protected void Add<T>(T source, MyEntities context, bool isNew) where T : class
{
    if (isNew)
    {
        context.Set<T>().Add(source);
    }
    else
    {
        var entry = context.Entry(source);
        if (entry.State == EntityState.Detached)
        {
            context.Set<T>().Attach(source);

            entry.State = EntityState.Modified;
        }
    }
}

执行时收到此错误这个:

I get this error when executing this:


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

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

它发生在 context.Set&T;()。Attach(source) / code>行。

It occurs on the context.Set<T>().Attach(source) line.

PS:这是一个跟随/脱离这个问题

PS: This is a followup/spin off of this question.

推荐答案

尝试这个

if (!context.Set<T>().Local.Contains(source))
 {
    context.Set<T>().Attach(source);
 }

context.Entry(source).State = EntityState.Modified;

这篇关于无法保存,因为“同一类型的另一个实体已经具有相同的主键值”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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