【发布时间】:2013-09-29 13:36:07
【问题描述】:
如何使用 NHibernate 创建一对一关系,而另一端可能为 NULL? 例如,我有一个 Banner 实体,它与 Image 实体有如下关系:
<class name="Banner" table="Banner">
<id name="Id" type="Int64" unsaved-value="0">
<generator class="native" />
</id>
<many-to-one name="Image" unique="true" column="ImageId" not-null="false"/>
<!-- check: In the example this property was without inverse attribute -->
<set name ="BannerSlideSet" fetch="subselect" inverse="true">
<key column="Banner_ID" foreign-key="FK_Banner_BannerSlide" not-null="false" />
<one-to-many class="BannerSlide"/>
</set>
</class>
因此,对于 Banner 实体,Image 可以为空。 我创建了一个没有图像的横幅实体,没有任何问题。 在数据库中我有
--------------
ID | ImageId
--------------
1 | NULL
之后,我尝试创建第二个不带图像的 Banner 实例,但出现以下错误:
NHibernate.Exceptions.GenericADOException:无法插入: [Domain.Entities.Banner][SQL: INSERT INTO Banner (ImageId) VALUES (?); 选择 SCOPE_IDENTITY()] ---> System.Data.SqlClient.SqlException: 违反 UNIQUE KEY 约束“UQ_横幅_7516F70DE6141471”。 无法在对象“dbo.Banner”中插入重复键。重复键 值为 ()。
我想,这是因为我对横幅和图像实体之间的一对多关系有唯一约束,并且几个横幅实例在 ImageId 字段中不能有多个 NULL 值。问题:如何在 NHinerbate 中实现一对空的关系?
谢谢!
【问题讨论】:
标签: c# .net nhibernate