NHibernate 一对一

标签 nhibernate

我在使用一对一映射时遇到问题。我搜索了互联网并找到了许多解决方案,但没有一个令人满意。大多数示例都带有将父实例存储在子类中的开销。

我只想在具有外键约束关系的子类中使用父 ID,但不想在子类中保留任何父实例。

当我尝试从数据库加载记录时,它抛出异常“不存在具有给定标识符的行 [AssemblyName.]”。但是,该记录正确存在于表“B”中。

这个问题有什么解决方案吗?

类(class)结构:

class A { 
public virtual string Id {get;set;} 
public virtual B B {get;set;} // properties...... } 

class B { public virtual string Id {get;set;} // properties...... 
public virtual string ParentId { get;set;} // class A Id }

数据库结构:
CREATE TABLE [A]( 
    [Id] [nvarchar](45) PRIMARY KEY
) ON [PRIMARY] 

CREATE TABLE [B]( 
    [Id] [nvarchar](45) PRIMARY KEY, 
    [ParentId] [nvarchar](45) NOT NULL
) ON [PRIMARY]

映射:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"> 
<class name="A,AssemblyName" table="A" lazy="true">
<id name="Id" column="Id" type="string"> 
<generator class="assigned"/> 
</id> 
<one-to-one name="_B" cascade="all" fetch="join" foreign-key="None" constrained="true" class="B"/> 
</class> 
</hibernate-mapping>


<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="B,AssemblyName" table="B" lazy="true"> 
<id name="Id" column="Id" type="string"> <generator class="assigned"/> </id>
<property name="_Name" column="Name"/> </class> 
</hibernate-mapping>

最佳答案

在 NHibernate 中,一对一的关联总是双向的。 B类的映射不完整:

<class name="B,AssemblyName" table="B" lazy="true"> 
   <id name="Id" column="Id" type="string">
      <generator class="assigned"/>
   </id>
   <many-to-one name="A" unique="true" column="A" />
   <property name="_Name" column="Name"/>
</class>

这是外键关联。如需更多信息,请参阅 this详细 Ayende 的博客文章或 NHibernate documentation .

关于NHibernate 一对一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6419329/

相关文章:

c# - session.Query 未从数据库获取更新的记录

nhibernate - 为一对多关系禁用自动\延迟加载子记录

asp.net - 使用 Nhibernate 在子查询中仅选择不带 group by 属性的 max 子句

c# - 如何让 NHibernate SchemaExport 创建 SQL Server 时间戳列?

c# - 在 NHIbernate 中使用带有公式的属性映射

c# - 容器不处理 transient 组件

c# - 使用 QueryOver 的 NHibernate OR

nhibernate - 如何在 Nhibernate QueryOver 中获取具有子项计数的父实体列表

NHibernate AssertException : Interceptor. OnPrepareStatement(SqlString)返回null或为空SqlString

c# - NHibernate HQL with isnull() 在哪里不起作用