Tamas Ionut
Tamas Ionut

Reputation: 4410

Composite Model insert issue in Fluent NHibernate

I have the following situation:

I have 2 classes (children) and a composite class (parent):

public Parent
{
   public ChildOne C1 {get;set;}
   public ChildTwo C2 {get;set;}
}

public ChildOne
{
    public int Id{get;set;}
...some primitive fields
}

public ChildTwo
{
    public int Id{get;set;}
...other primitive fields
}

THe mapping for these classes is the following:

public class Parent: ClassMap<Parent>
    {
        public ParentMap()
        {
            Table("Parents");
            Id(x => x.Id).Column("ParentId"); 
            References(x => x.C1).Column("ChildOneId");
            References(x => x.C2).Column("ChildTwoId");
        }
    }

and

public class ChildOne: ClassMap<ChildOne>
    {
        public ChildOneMap()
        {
            Table("ChildOnes");
            Id(x => x.Id).Column("ChildOneId"); 
            ...other Mappings for primitive types
        }
    }

(and the same for ChildTwo).

The DB is as follows:

Parents: ParentId, ChildOneId, ChildTwoId
ChildOne: ChildOneId, ...other columns
ChildOne: ChildTwoId, ...other columns

and the relationships ChildOneId (Parents)<==>ChildOneId (ChildOnes).

When I want to insert a new Parent in the Db with the corresponding children, I get an error that ChildOneId/ChildTwoId cannot be null.

What do I need to specify in the mapping class in order for the insert to work? (The retrieve operation works properly)

Thanks, Tamash

Upvotes: 0

Views: 128

Answers (1)

Firo
Firo

Reputation: 30803

i guess you dont call save on the childs.

session.Save(new Parent { C1 = new ChildOne(), C2 = new ChildTwo() });

Use cascading to perform saving the childs from the parent.

References(x => x.C1).Column("ChildOneId").Cascade.All();
References(x => x.C2).Column("ChildTwoId").Cascade.All();

Upvotes: 1

Related Questions