I have a problem with one-to-one relationships in NHibernate. The structures of the my objects are as follows:
public partial class PersonDataContext
{
protected int _personid;
protected string _name;
protected EmployeeDataContext _employee;
}
public partial class EmployeeDataContext
{
protected int _personid;
protected string _payrollno;
}
In my model, every PersonDataContext must contain exactly one EmployeeDataContext, and every EmployeeDataContext that exists is there to be part of an PersonDataContext . It's a common one-to-one relationship.
Now, to the mappings:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="PersonDataContext, DAL" table="`Person`" lazy="false">
<id name="PersonId" column="`PersonId`" type="int">
<generator class="native" />
</id>
<property type="string" name="name" column="`name`" />
<one-to-one name="Employee" cascade="save-update" class="EmployeeDataContext,DAL" />
</class>
</hibernate-mapping>
<hibernate-mapping xmlns="开发者_开发问答urn:nhibernate-mapping-2.2">
<class name="EmployeeDataContext, DAL" table="`Employee`" lazy="false">
<id name="PersonId" column="`PersonId`">
<generator class="foreign">
<param name="property" >PersonId</param>
</generator>
</id>
<property type="string" length="30" name="PayRollNo" column="`PayRollNo`" />
</class>
</hibernate-mapping>
Then I create an PersonDataContext, that creates by itself an EmployeeDataContext. Then when I save it NHibernate throws an exception, "Unable to resolve property: PersonId".
You don't have a PersonId property in EmployeeDataContext.
You should have a PersonDataContext property of type PersonDataContext, and that's what goes in the param.
The foreign property error, modify 'PersonId' to 'PersonDataContext' as follow:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="EmployeeDataContext, DAL" table="`Employee`" lazy="false">
<id name="PersonId" column="`PersonId`">
<generator class="foreign">
<param name="property" >**PersonDataContext**</param>
</generator>
</id>
<property type="string" length="30" name="PayRollNo" column="`PayRollNo`" />
</class>
</hibernate-mapping>
精彩评论