简体   繁体   中英

Silverlight & RIA & POCO: SubmitOperationFailed when INSERTING two new child entities. An entity with the same ID exists

Here's my scenario:

I am using Silverlight, RIA and POCO objects (no Entity Framework; we're working against Oracle and SP's).

I have a Parent object that contains a collection of Child objects. I have setup the Association and Composition attributes on the Parent correctly. When I want to save changes, the entire object graph gets sent to the server correctly.

The user can add one or more Child objects to the Parent.

Now, if the user adds ONE Child object to the Parent and saves it then everything works. However, when the user tries to add TWO or more new objects to the Parent and then persist, I get the classic error:

System.ServiceModel.DomainServices.Client.DomainOperationException: Submit operation failed. An entity with the same identity already exists in this EntitySet. ---> System.InvalidOperationException: An entity with the same identity already exists in this EntitySet.

Now, this is failing on the client. I am tracing everything - the database actually gets updated! Everything gets sent down to the server correctly, the DB gets updated. I check the object keys on the server when the re-query happens and they are correct - all of the new child objects get their ID's updated from zero to a real number in sequence.

It's when I get to re-load the Parent object on the client that I get this error. I don't get it. I am newing up a new Context on the re-load operation; it should be empty and just load the Parent and associated Children. I check the data on the server side before it goes out of the query method - the parent and child data is fine. So what's happening? Why is my context bitching about not being able to complete this SubmitOperation?

You gave up too easy - don't let RIA do it for you!! :-)

Here is the deal...

Since you are working with POCO objects (no EF) you most likely have an identifying attribute ([Key]) on one of your properties designating it the key (or identity) of that object.

Well...

When you add 2 consecutive objects, you will most likely default the value of your key to a value of 0. This is a problem for the domain service & context because it attempts to manage the set for you. Well, if after the saving of the objects to the database, you have not updated the key they will both remain with a value of 0.

Problem!

The domain service & context attempt to put these two objects in its managed EntitySet and, as such, all objects must be unique.

So...

Long and the short of it is... update your key value after saving it to the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM