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

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

问题描述

我有这个控制器的动作:

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:

附加类型的实体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&LT; T&GT;()将(源)

PS:这是一个后续/分拆的这个<一个href=\"http://stackoverflow.com/questions/34289369/second-call-to-same-dbcontext-causes-error-dbcontext-has-been-disposed/34290947#34290947\">question.

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天全站免登陆