NHibernate双向一对一映射问题

NHibernate双向一对一映射问题,nhibernate,bidirectional-relation,Nhibernate,Bidirectional Relation,在尝试在NHibernate中创建双向一对一映射时,我发现,我无法递归地获得对象的引用 例如:假设我在Person和Address之间有一对一的关系 然后在执行下面的代码之后 class Person { ... ... public Address Address { get;set; } } class Address { ... ... public Person Person {get;set;} } Repository<Person>

在尝试在NHibernate中创建双向一对一映射时,我发现,我无法递归地获得对象的引用

例如:假设我在
Person
Address
之间有一对一的关系

然后在执行下面的代码之后

class Person
{
    ... ...
    public Address Address { get;set; }
}

class Address
{
    ... ...
    public Person Person {get;set;}
}

Repository<Person> rep = new Repository<Person>();
Person p = rep.Get<Person>(1);
Person.hbm.xml
一对一关联有两种类型:

•主键关联

•独特的外键关联

主键关联不需要额外的表列;如果两行由关联关联关联,则 两个表行共享相同的主键值。因此,如果希望两个对象通过主键关联进行关联, 您必须确保为它们分配了相同的标识符值! 对于主键关联,分别向Employee和Person添加以下映射

<one-to-one name="Person" class="Person"/>
<one-to-one name="Employee" class="Employee" constrained="true"/>

现在我们必须确保PERSON表和EMPLOYEE表中相关行的主键相等

我们使用一种特殊的NHibernate标识符生成策略,称为foreign:

<class name="Person" table="PERSON">
<id name="Id" column="PERSON_ID">
<generator class="foreign">
<param name="property">Employee</param>
</generator>
</id>
...
<one-to-one name="Employee"
class="Employee"
constrained="true"/>
</class>

雇员
...
然后,将为新保存的Person实例指定与引用的Employee实例相同的primar键值 该人的雇员财产。 或者,员工之间具有唯一约束的外键可以表示为:

<many-to-one name="Person" class="Person" column="PERSON_ID" unique="true"/>

通过将以下内容添加到人员映射中,此关联可以双向进行:

<one-to-one name="Employee" class="Employee" property-ref="Person"/>

资料来源:

看看这个


发布个人和地址的映射文件可能会有好处。从个人到多和从地址到多我很困惑。u plz能给我提供db表列吗?@JMSA你能告诉我你的两个个人和地址表的关系吗?i、 您是否将PERSON表主键放在ADDRESS表中,或者对这两个表使用相同的主键?我有表,ADDRESS{ID,Desc}和PERSON{ID,Name,AddressID}。也就是说,AddressID是一个FK-in-Person表。@JMSA看看我添加到答案中的链接。
<one-to-one name="Person" class="Person"/>
<one-to-one name="Employee" class="Employee" constrained="true"/>
<class name="Person" table="PERSON">
<id name="Id" column="PERSON_ID">
<generator class="foreign">
<param name="property">Employee</param>
</generator>
</id>
...
<one-to-one name="Employee"
class="Employee"
constrained="true"/>
</class>
<many-to-one name="Person" class="Person" column="PERSON_ID" unique="true"/>
<one-to-one name="Employee" class="Employee" property-ref="Person"/>