Gage
Gage

Reputation: 7513

Better way to manage Nhibernate Relation table

I am wondering if there is a better way to manage relation tables in Nhibernate. Currently when the user first creates A I can just call .Save and everything is fine. But when they load it and make changes, I don't simply want to delete all the corresponding records and recreate them. I want it to deletes the records that are no longer valid and create the ones that are new and leave the ones that are still valid and in the database alone.

Currently I look through the list and delete the ones that aren't selected anymore then add the ones to the list that are new. Doesn't seem like the best way though since I'm looping through the list twice. Is there LINQ one liner solution out there?

Basically what I'm currently doing:

Loop through A and delete whats not in B
Loop through B and add whats not in A

Thanks in advance.

Upvotes: 2

Views: 142

Answers (1)

Stefan Steinegger
Stefan Steinegger

Reputation: 64658

Not sure what your A's and B's actually are.

If they are children of some root entity, you could use cascade="all-delete-orphan". NH will delete all children which are not in the list anymore.

If you manage a list of root entities, you need to go through this "find added items / find removed items" business.

var removedItems = oldList.Except(newList);
var addedItems = newList.Except(oldList);

Upvotes: 3

Related Questions