views:

676

answers:

1

I have a typical parent/child relationship. Writing news in .NET and adding children works fine, NHibernate plays nice and adds the correct relationships. However, when passing a JSON object from the client to some method that serializes my JSON into the .NET representation, NHibernate seems to get confused. It comes up with the correct query to add the parent (and assigns a new guid for Id), however, it doesn't associate that parent id to the children objects in the sql it tries to execute. I came up with a quick and dirty hack, which I list below - But I was wondering, is there something I'm missing here?

IList<BackerEntry> backersTemp = new List<BackerEntry>();
foreach (BackerEntry backerEntry in jsonBackerEntity.BackerEntries)
{
  backersTemp.Add(backerEntry);
}

jsonBackerEntity.BackerEntries.Clear();

foreach (BackerEntry backerEntry in backersTemp)
{
  jsonBackerEntity.AddChild(backerEntry);
}

Doing it that way is the only way I can seem to get NHibernate to see that these children really belong to this parent. Inside my AddChild method looks like this:

public virtual void AddChild(BackerEntry backerEntry)
{
  if (backerEntry.Backer != null)
  {
    backerEntry.Backer.BackerEntries.Remove(backerEntry);
  }
  backerEntry.Backer = this;
  this.BackerEntries.Add(backerEntry);
}

EDIT: I think I may have just realized why - Probably because I am not sending back the Parent property of the child in the JSON. I'm not even sure if that'd be possible, due to the circular nature of the two. Child has a parent (who in json has a child who is the original child who has a parent, etc)... Any ideas?

+1  A: 

That's right - nhibernate won't automatically create the association in the inverse direction. I think that all you need to do is:

foreach(BackerEntry entry in jsonBackerEntity.BackerEntries)
{
  entry.Backer = jsonBackerEntity;
}
Isaac Cambron