Search code examples
nhibernatefluent-nhibernateone-to-manycomposite-key

Nhibernate one to many relationship composite key issue


Below is my Parent child relationship class and mapper. We are using Nhibernate 4.0.0.4000 in our project. When I call session.Merge(Parent) to update the parent which has a new child object to insert into Db. It throws cannot insert Null exception for code_column in child object. Can somebody guide which part in my mapper code is wrong?

Public class parent {
  public virtual string Code { get; set; }
  public virtual string Desc { get; set; }
  public virtual IList<Child> Children{ get; set; } 
  public virtual int version {get;set;}
}

Public class Child {
  public virtual parent ParentObj{ get; set; }
  public virtual string Code1{ get; set; }
  public virtual string Code2{ get; set; }
  public virtual int version {get;set;}
}


public class ParentMap : ClassMap<Parent> {
public ParentMap () {
   Table("Parent_Table");
            LazyLoad();
            OptimisticLock.Version();

  Id(x => x.Code )
           .Column("Code_Column")
           .Index("Code_IDX1")
           .Length(5)
           .Unique()
           .GeneratedBy.Assigned()
           .Not.Nullable();

            Version(x => x.Version)
                .Column("VERS")
                .UnsavedValue("0");

            HasMany(x => x.Children)
                  .AsBag()
                .KeyColumn("Code_Column")
                .Inverse()
                .LazyLoad()
                .Cascade.All();
}

}


public class ChildMap: ClassMap<Child> {
public ChildMap() {
 Table("Child_Table");
            LazyLoad();
            OptimisticLock.Version();

            CompositeId()
                .KeyReference(u => u.Code, "Code_Column")
                .KeyProperty(u => u.Code1, "CODE1_column")
                .KeyProperty(u => u.Code2, "CODE2_column");

            Version(x => x.Version)
             .Column("VERS")
             .UnsavedValue("0");
}

}

Solution

  • It was the composite Id which had the issue with session.merge method probably because of the lazy load. When you have composite keys, Create a class for the composite keys and use them in your entity which would work fine.