views:

135

answers:

2

I have two NHibernate-managed entities that have a bi-directional one-to-many relationship:

public class Storage
{
    public virtual string Name { get; set; }
    public virtual IList<Box> Boxes { get; set; }
}

public class Box
{
    public virtual string Box { get; set; }
    [DoNotSerialize] public virtual Storage ParentStorage { get; set; }
}

A Storage can contain many Boxes, and a Box always belongs in a Storage. I want to edit a Box's name, so I send it to the client using JSON. Note that I don't serialize ParentStorage because I'm not changing which storage it's in.

The client edits the name and sends the Box back as JSON. The server deserializes it back into a Box entity.

Problem is, the ParentStorage property is null. When I try to save the Box to the database, it updates the name, but also removes the relationship to the Storage.

How do I properly serialize and deserialize an entity like a Box, while keeping the JSON data size to a minimum?

A: 

I would guess that ParentStorage is null because it is being lazily loaded. Either configuring it to be fetched eagerly or forcing a read by calling the getter before serialization may help make sure the Storage is serialized, and depending on your ID scheme this may work (I don't know for sure).

The gains from serialization in this case seem minimal, and may have unexpected consequences as the Box and Storage classes evolve. It seems simpler to send up a single string for the name, load the Box, set the string, and save that object. Then you don't have to worry as much about the optimizations Hibernate does underneath.

David C
That's wrong, lazily loaded relationships are not null, they are assigned to proxies.
Diego Mijelshon
A: 

I would recommend you send a DTO to the client for display purposes (and it should contain the unique database ID). Then send the boxId + the new name back up to the server from the client (there is no need to send the entire DTO back). The server can do a database lookup using the ID to get the box object, update the name field to the one sent from the client, and save the box to the database.

There is no need in this scenario to serialize an NHibernate object, that just adds a lot of complexity and no value.

Michael Maddox