解决的最佳实践“ObjectStateManager中已存在具有相同键的对象”错误

时间:2013-11-05 08:31:23

标签: c# entity-framework

当然你知道为什么会出现以下错误

  

ObjectStateManager中已存在具有相同键的对象。 ObjectStateManager无法跟踪具有相同对象的多个对象   键。

我想要更新或删除它的实体

var p = new Person() // for delete
        {
            Id = 3,
            Name = "A",
            Family = "A",
            Age = 10
        };
var p2 = new Person() // for update
        {
            Id = 3,
            Name = "W",
            Family = "W",
            Age = 90
        };

我的目标是在代码下方使用,但在使用时会出现错误

var attachedEntity = leitner.Set<Person>().Attach(p); // maybe not needed !!! according to @oerkelens comment
        leitner.Entry(attachedEntity).State = EntityState.Deleted; // for delete
        leitner.Entry(attachedEntity).State = EntityState.Modified; // for update
        leitner.SaveChanges();

所以我必须改变它,如下面的代码

var attachedEntity = leitner.Set<Person>().Local.SingleOrDefault(x => x.Id == 3);

        attachedEntity.Name = "W"; // for update
        attachedEntity.Family = "W";// for update
        attachedEntity.Age = 90;// for update

        leitner.Entry(attachedEntity).State = EntityState.Deleted;// for delete

        leitner.Entry(attachedEntity).State = EntityState.Modified;// for update

        leitner.SaveChanges();

新代码有效但我有两个问题

首先:我必须手动搜索ID

SingleOrDefault(x => x.Id == 3) // for update or delete

第二:我必须逐个为属性设置值

        attachedEntity.Name = "W"; // for update
        attachedEntity.Family = "W";// for update
        attachedEntity.Age = 90;// for update

我无法将我的实体分配给attachmentEntity

attachedEntity = p; // does not work same error as above occures
attachedEntity = p2; // does not work same error as above occures

请指导我访问我的目标

我的目标是这样的:

 var attachedEntity = leitner.Set<Person>().Attach(p); // may be not needed !!!

        leitner.Entry(attachedEntity).State = EntityState.Deleted; // if only use this line above error occures again

     leitner.Entry(attachedEntity).State = EntityState.Modified; // if only use this line above error occures again

        leitner.SaveChanges();

立即设置整个“p”(实体),无需逐个设置

1 个答案:

答案 0 :(得分:0)

您已经获得了查找实体的代码,但您应该注意.Local仅在先前已从数据库中提取实体或附加到当前会话的其他位置时才有效。

var attachedEntity = leitner.Set<Person>().SingleOrDefault(x => x.Id == 3);

Remove

上有DbSet方法
leitner.Set<Person>().Remove(attachedEntity);

SetValues

返回的DbEntityEntry<Person>上的leitner.Entry(attachedEntity)方法
var p2 = new Person() // for update
    {
        Id = 3,
        Name = "W",
        Family = "W",
        Age = 90
    };
leitner.Entry(attachedEntity).Currentvalues.SetValues(p2);