开发者

EF4 - Updating the same table row twice in the same context from different objects not possible?

When I receive the same table row twice for updating in the same context I get:

"AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges."

The problem happens at the ChangeState method.

What I have can be simplified to this:

        var obj1 = new test() { id = 1,name = "oiu"};
        var dc = Context.Create();

        dc.test.AddObject(obj1);
        if (dc.test.Any(a => a.id == obj1.id))
            dc.ObjectStateManager.GetObjectStateEntry(obj1).ChangeState(EntityState.Modified);
        dc.SaveChanges();

        //---- another iteration of the reading thread, another object, but same context:

        var obj2 = new test() { id = 1, name = "ois" };
        dc.test.AddObject(obj2);
        if (dc.test.Any(a => a.id == obj2.id))
            dc.ObjectStateManager.GetObjectStateEntry(obj2).ChangeState(Enti开发者_运维知识库tyState.Modified);
        dc.SaveChanges();

Is there a way out or around?


So, what are you trying to do? You've told EF and the database (I assume) that "id" is the unique identifier for an object/row. Then, you've told it that you want to add two objects with the same unique id (of "1") and expecting it to handle work.

Do you want to add to objects with the same unique ID, or do you want to add one, then update that existing row/object to change the name property from "oiu" to "ois". If it's the former, don't make "id" a pkid. if it's the latter, don't tell EF that you want to add the object twice. Add it once, the update the existing object.


You can connect object to the context only once (by either loading the object from the database or calling Attach or AddObject). Once you connect the object to the context it is your responsibility to use the same instance for all modification. The context uses identity map pattern - it means that it tracks objects by their unique identification (Entity key based on primary key and entity set) and allow only one instance of the type with given entity key. The only exception is adding new objects where EntityKey is temporary until saving changes but it is not the case if you change state to Modified.

If you don't know the instance in the rest of your test you can query ObjectStateManager.GetObjectStateEntries and search for your instance (each entry has Entity property referencing the instance).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜