由于'another entity of the same type already has the same primary key value'无法保存



我有这个控制器操作:

[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);
}

在这种保存方法的深层次被称为:

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;
        }
    }
}

我在执行这个时得到这个错误:

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

它出现在context.Set<T>().Attach(source)线上。

附言:这是这个问题的后续/衍生。

尝试这个

if (!context.Set<T>().Local.Contains(source))
 {
    context.Set<T>().Attach(source);
 }
context.Entry(source).State = EntityState.Modified;

相关内容

最新更新