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?
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.