tags:

views:

84

answers:

2

Hi all,

I ve got the following setup:

public class ParentEntity
{
   public ICollection<ChildEntity> {get; set; }
}

public class ChildEntity
{
   // do i need to the parent here?
}

I managed to save the ParentEntity and cascaded the save to the added child entities which were saved as well. But in the db table the ParentId reference of the child was set to allow NULL. When setting it to NOT NULL the save failes since the ParentId in the child table is NULL.

What's happening there? ;)

When

+1  A: 

You should map both sides of the relationship normally, and when you add a child to the parent's collection, you should also set the parent property on the child. Normally you would achieve this by writing a method like this:

public void AddChild(ChildEntity child)
{
   this.Children.Add(child);
   child.Parent = this;
}

NHibernate persists the ParentId column in the Child table based on the mapped property in the ChildEntity class. The definition of the one-to-many relationship merely allows NHibernate to load the collection from the database based on values in this column

David M
You don't do that normally. When you do this for everything, almost all your entities will be coupled to each other (spaggetti code when the app gets larger) and it will not be possible to use bounded context. Some relations need to be bidirectional, especially when the parent and the child are both aggregate roots, but when the parent is responsible for it's children, which is most of the time, a unidirectional relationship will be better.
Paco
A: 

I am having the same issue and need this to either have nHibernate expose the foreign key column, or do it in class via collection.

Problem: nHibernate creates the collection object (IList, for example) and you can not override the or listen to the add events of basic collections.

This becomes an issue only because it is required by the WCF RIA Services framework.

Bytemaster