0

I can't understand why NHibernate is inserting a child entity without the foreign key of the parent. The only way I found to solve this is with a Bidirectional relationship, is there another way?

Here are the classes:

public class Parent
{
    public virtual int ParentId {get; private set;}
    public virtual IList<Child> Notes {get; private set;}
}

public class Child
{
    public virtual ChildId {get; private set;}
    public virtual Name {get; private set;}
}

Here is my Fluent NHibernate mapping

public class ParentClassMap : ClassMap<Parent> 
{
    public ParentClassMap(){
        Id(x => x.ParentId);
        HasMany(x => x.Notes).Cascade.AllDeleteOrphan();
    }
}

public class ChildClassMap : ClassMap<Child> 
{
    public ChildClassMap() {
        Id(x => x.ChildId);
        Map(x => x.Name);
    }
}

When I add a child to the parent's child collection and save the parent, the parent and the child are inserted into the database, but the child is inserte withoutthe foreign key to the parent (it has a null value)

This is the insert that is generated:

INSERT INTO Child(ChildId, Name)

But it should be:

INSERT INTO Child(ChildId, Name, ParentId)

I want to add that i don't want to resolve this with a bidirectional relationship, i do not want the child to have a reference to the parent. Thanks!!

2 Answers2

1

Add Not.KeyNullable() to your HasMany mapping.

Note: This feature requires NHibernate 3.2.

cremor
  • 6,669
  • 1
  • 29
  • 72
-1

Your parent class mapping should have an inverse for its child

public class ParentClassMap : ClassMap<Parent> 
{
    public ParentClassMap(){
        Id(x => x.ParentId);
        HasMany(x => x.Notes).Cascade.AllDeleteOrphan().Inverse();
    }
}

Thanks Neelesh

Neelesh
  • 475
  • 3
  • 16
  • This would result in no saving operation at all since there is no bidirectional association. – cremor Sep 16 '11 at 07:01
  • You are quite right in what you said. Is there any particular why you are not making the relationship become bidirectional? – Neelesh Sep 16 '11 at 07:14
  • Most likely because the bidirectional association is not needed (or wanted) in the domain classes. Having an object reference just for saving it is not very "persistence ignorant". – cremor Sep 16 '11 at 07:24