1

您当然知道为什么会发生以下错误

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

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

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”(实体),无需一一设置

4

1 回答 1

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);
于 2013-11-05T10:55:40.460 回答