Not sure what the “preferred method” will be (this may depend on who prefers it). But I can share my way.
If the parent is the root object, then we must save the entire link tree in one frame: session.SaveOrUpdate(parent) .
eg. Employee has a set of Educations . In this case, it should look like this
- create
Education give a link to the employee, Add() to the employee.Educations collection.- Have / reverse the mapping, cascade = "all-delete-orphan" ...
- NHibernate will do what we expect from session.SaveOrUpdate (parent)
Some snippets in xml:
<class name="Employee" table="..." lazy="true" optimistic-lock="version" dynamic-update="true" batch-size="25" > <cache usage="read-write" region="ShortTerm"/> <id name="ID" column="Employee_ID" generator="native" /> <bag name="Educations" lazy="true" inverse="true" batch-size="25" cascade="all-delete-orphan" > <key column="Employee_ID" /> <one-to-many class="Education" /> </bag> ...
And education
<class name="Education" table="..." lazy="true" batch-size="25> <cache usage="read-write" region="ShortTerm"/> <id name="ID" column="Education_ID" generator="native" /> <many-to-one not-null="true" name="Employee" class="Employee" column="Employee_ID" /> ...
on the run:
public class EmployeeMap : ClassMap<Employee> { public EmployeeMap() { BatchSize(25) ... HasMany(x => x.Educations) .AsBag() .BatchSize(25) .LazyLoad() .Cascade.AllDeleteOrphan() .Inverse() .KeyColumn("Employee_ID") public class EducationMap : ClassMap<Education> { public EducationMap() { ... References(x => x.Employee, "Employee_ID") .Not.Nullable() ...
And now the C # relationship:
// business var employee = ...; var education = new Education { Employee = employee, ... }; employee.Educations.Add(education); // DAO session.SaveOrUpdate(employee);
If the parent is not root, only the relation exists ( Employee has a set of Subordinates type Employee ), keep the persistent shared
source share