Swaping a unique key value between two entities

Posts   
 
    
Courela
User
Posts: 3
Joined: 05-Jan-2006
# Posted on: 09-Feb-2006 16:47:16   

Hi, i'm trying to update two entities by swaping a field that is a unique key. I do this in a recursive save, which uses transactions, but i'm getting an error from the database saying that it can't save the entity because of the unique key constrain.

The scenario is: i have an entity called Form that holds a collection of entities called Sections. The Sections have a field indicating Forms' Id and a field called OrderIndex. The two fields perform the unique key constrain. I swap the OrderIndex of two Sections in the Forms' collection and performed a Save(true) in the Form. This generates the error.

What's wrong in this scenario? Btw i'm using Self-Servicing, if it matters.

bclubb
User
Posts: 934
Joined: 12-Feb-2004
# Posted on: 10-Feb-2006 03:28:59   

I would imagine you are having your problem because you can't perform the switch without causing the duplicate. The best solution I can think of off the top of my head is to set one to a temp value that would never be set in the key, perform the update of the other entity and then set the temp value back to what you originally wanted.

It's a little picky how it has to work though. The first entity to be saved in the collection needs to be saved as the 9999 temporary value. So A must be in the collection before B.

The field g is the unique key, or the portion that you are changing.

int originalValue = B.g; B.g = A.g; A.g = 99999; collection.SaveMulti(true); A.g = originalValue; A.Save();

This seems like a bad hack, if someone has a better solution don't hesitate to chime in. But this is the first thing that came to mind.