I have the following entities (with the ID property ommitted for brevity):
Code:
public class Storage
{
public string Name { get; set; }
public IList<Box> Boxes { get; set; }
}
public class Box
{
public string Name { get; set; }
public Storage ParentStorage { get; set; }
public IList<Item> Items { get; set; }
}
public class Item
{
public string Name { get; set; }
public Box ParentBox { get; set; }
}
In plain English, a Storage can have a bunch of boxes, and a box can contain multiple items. Each relationship is bi-directional, so you can navigate from the storage all the way down to an item, and then back up again.
Now, let's say we already have some data in the database. What I want to do is get a box from the database, send it to the UI (in this case, a web browser), change the box's name, and send it back to the server and save it. This box contains items.
Because the client is a browser, I have to serialize the box. It makes no sense for me to send over the entire object graph, so I just send over the box entity with its name and ID. The user edits the name in a HTML form, then sends back the box entity.
On the server side, I receive the FORM POST sent by the browser and de-serialize it back into a box. This is where I'm having problems. When the box is de-serialized, it has the same ID as the persistent one in the database, but the reference to its ParentStorage and collection of Items is null/empty. If I attempt a Merge(), NHibernate replaces the persistent copy with the one I sent back from the server, along with the null references. In essence, Merge() deletes the relationships because they don't exist in my 'updated' entity.
My question is, how do I preserve the entity relationships without explicitly sending them back and forth? This was a very simple example. In my real application, I have some classes with a lot of simple properties and relationships to 4 or more other classes. Theoretically, I could get the persistent box from the database and do a field-by-field copy-and-paste, but that seems like a lot of hard-to-maintain, boiler-plate code that NHibernate should be handling. Any help would be greatly appreciated.