开发者

Fluent NHibernate insert parent id problem with HasMany relationship

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!!


Add Not.KeyNullable() to your HasMany mapping.

Note: This feature requires NHibernate 3.2.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜