Nhibernate foreign key as composite key

Hi, I'm pretty new to Nhibernate, and I'm working on a project that is described as follows:

1 Parents table containing ParentName and one for many ChildList using IList, with Primary Key set to ParentId

1 Children table with a composite primary key that contains ParentID as one of the keys

so I installed one-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 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 I'm currently doing a test to save Parent obj with some Children in list to MySQL database using the session.SaveOrUpdate method, but it always fails and just said “can't paste” 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);

, . . - , , ParentName in Children , , ParentName Parent , , .

, , obj ? ( PK, , , , )

Parent parent= session.CreateCriteria(typeof(Parent))
                    .Add(Restrictions.Eq("ParentName", ParentName))
                    .UniqueResult<Parent>();
NHibernateUtil.Initialize(parent.ChildrenList);

!

+3

Source: https://habr.com/ru/post/1758700/


All Articles