Stumblor
Stumblor

Reputation: 1140

Json.NET and NHibernate - Deserializing a Persistent Object

I'm sending a JSON collection from Javascript through a REST web service to be Deserialized using Json.NET and then finally updated in the DB using NHibernate (I'm using Fluent). The settings I'm using for Json.NET Deserialization are:

        JsonConvert.DeserializeObject<T>(jsonString,
        new JsonSerializerSettings { 
            PreserveReferencesHandling = PreserveReferencesHandling.Objects
        });

My Json object is:

{
  "ID": 1,
  "Name": "ObjectName",
  "Keys": [
    {
      "ID": 6,
      "Name": "ID"
    }
  ]
}

Modifying properties of the object, and even adding and modifying the child objects (Keys) and then deserializing works great. However, i can't seem to work out how to manage child object deletes. For example, if I remove a child object (using Object.Keys.splice), and then update, the DB record it relates to remains persistent even though the parent object which is updated does not contain them.

Additionally, I have also set 'AllDeleteOrphan' in the mapping file.

    // one-to-many
    HasMany(x => x.Keys)
      .Inverse()
      .Cascade.AllDeleteOrphan();

Is there any way to ensure that child objects removed via javascript will be cascade deleted when the object is deserialized and updated?

I have also read that when using NHibernate, child objects need to be removed manually from the parent collection, via Keys.Remove(item), before update. It would be much more preferable (not to mention scalable) to just deserialize and update. Any chance?

Upvotes: 2

Views: 1598

Answers (1)

ddango
ddango

Reputation: 956

You should be able to update and then see those changes cascade, but I believe the issue has to do with the collection being marked as inverse.

Inverse=true (which is fluent nhibernate's .Inverse() is binding) is like saying "I do not manage this relationship". Due to this binding, the parent object is not deleting/updating the collection because the children manage the relationship.

Whether this makes sense or not, I could not really say without a fuller understanding of your domain.

Upvotes: 2

Related Questions