Unable to save because of 'another entity of the same type already has the same primary key value'

隐身守侯 提交于 2020-01-07 03:05:45

问题


I have this Controller action:

[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:

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.

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

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


回答1:


try this

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

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


来源:https://stackoverflow.com/questions/34291602/unable-to-save-because-of-another-entity-of-the-same-type-already-has-the-same

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!