Delete collection then insert replacement with a UnitOfWork

Posts   
 
    
johnsmith
User
Posts: 19
Joined: 14-Dec-2004
# Posted on: 30-Jan-2007 12:28:43   

What is the best way to delete a collection and then insert a replacement collection in a single transaction?

For example, I've made some changes to a User's UserGroup collection and now I want to replace the existing collection in the database with the new one so:

UnitOfWork uow = new UnitOfWork();
uow.AddCollectionForDelete(new UserEntity(user.UserId).UserGroup);
uow.AddCollectionForSave(user.UserGroup);
uow.Commit(new Transaction(IsolationLevel.ReadCommitted, "ReplaceUserGroups"), true);

But after the commit I lose any existing UserGroups from the database, presumably because the delete is happening after the insert in the UnitOfWork.

What is the correct approach here? Thanks, J.S.

johnsmith
User
Posts: 19
Joined: 14-Dec-2004
# Posted on: 30-Jan-2007 13:01:22   

Okay, now I'm confused. It seems the same effect occurs even when the delete and insert are two separate transactions, i.e.

new UserEntity(user.UserId).UserGroup.DeleteMulti();
user.UserGroup.SaveMulti();

Any UserGroups for the given user which were already in the database are not inserted by the SaveMulti even though they're still there in the user.UserGroup collection.

What's happening?

jmeckley
User
Posts: 403
Joined: 05-Jul-2006
# Posted on: 30-Jan-2007 14:21:59   

in your second model are you committing the transaction? if you begin a transaction, but don't close the transaction, it will rollback when the connection is closed.

Aurelien avatar
Aurelien
Support Team
Posts: 162
Joined: 28-Jun-2006
# Posted on: 30-Jan-2007 15:45:49   

Hi,

I guess entities in user.UserGroup collection are not new. (you get them from your DB with a fetch). In this case, no insert will bo processed. To save these entities, you should set the IsNew Property to True for each of them, and save.