Hi I am pretty new to Nhibernate and I am working on a project that is described as follow:
1 "Parents" table containing ParentName and a one to many ChildrenList using IList, with Primary Key set to ParentId
1 "Children" table , with a composite primary key that contains ParentID as one of the key
so I set up a one to many in Parents.hbm.xml like this
<class name="ParentName " table="Parents">
<id name="ParentName " column="ParentName ">
<generator class="assigned"/>
</id>
<property name="ParentAlpha" />
<bag name="ChildrenList" cascade="all">
<key column="ParentName" />
<one-to-many class="Children"/>
</bag>
and the Children.hbm.xml like this
<composite-id>
<key-many-to-one name="ParentName" class="Parent"/>
<key-property name = "ChildrenAlpha" />
<key-property name = "ChildrenAlpha2"/>
</composite-id>
<property name="ChildrenBeta" />
<property name="ChildrenGama" />
And currently im doing test on saving Parent obj with some list of Children in to a MySQL database using the session.SaveOrUpdate method, but it always fails and just said "cannot insert "the Children Obj
Here is my test code:
Parent parent = new Parent(){ParentAlpha= "ABC"};
Children children = new Children(){ChildrenAlpha = "AAA" ,ChildrenAlpha2 ="VBB"};
parent .ChildrenList.add(children); //IList add function
.....session.SaveOrUpdate(parent);
I have tested for one parent to many children, and the children primary key is set to a generated ChildrenId. and this works fine. But somehow I cannot do it using composite key, my guess is that as ParentName in Children is a primary key but will only be filled after ParentName in Parent has been filled, well sth like that.
Another Question is that if the above problem is solved, can i use this to retrieve the whole parent obj with the children list? ( I tried it for simple single PK case but seems not working when children is a composite key thing)
Parent parent= session.CreateCriteria(typeof(Parent))
.Add(Restrictions.Eq("ParentName", ParentName))
.UniqueResult<Parent>();
NHibernateUtil.Initialize(parent.ChildrenList);
Thanks!