NHibernate多对一和唯一约束违反 [英] NHibernate many-to-one and unique constraint violation

查看:354
本文介绍了NHibernate多对一和唯一约束违反的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,试图在NHibernate中建模一个多对一的关系,其中一方对象有一个列的唯一约束。问题如下:

I have a problem trying to model a many-to-one relationship in NHibernate, where the object on the 'one' side has a unique constraint on a column. The problem is as follows:

我有两个表,'Person'和'Country'。每个人都有一个且只有一个国家与其相关联。一个国家可以有多个人(真的!:))和一个国家的名称是唯一的。以下是Person侧的映射:

I have two tables, 'Person' and 'Country'. Each Person has one and only one Country associated with it. A Country can have many Persons (really! :)) and a Countries' Name is unique. The following is the mapping on the Person side:

<many-to-one Name="Country">
<column Name="CountryId"/>
</many-to-one>

在国家/地区:

<property name="Name" unique="true">
<column name="Name" length="50">
</property>

现在在数据库中,我在Country表中的Name列添加了一个唯一约束。如果我在Person实例上调用Save(),NHibernate只是尝试执行INSERTS,而我希望它检查国家名称是否存在,并在Person表的CountryID列中使用它的ID。相反,会抛出由于违反数据库中的唯一约束而导致的异常。

Now in the database I have added a unique constraint on the Name column in the Country table. If I call Save() on a Person instance NHibernate just tries to do INSERTS, whereas I would expect it to check if a Country Name exists and use its ID in the CountryID column in the Person table. Instead, an exception is thrown that results from violation of the unique constraint in the database.

在我看来,Nibernate应该有足够的映射元数据来做正确的事情(或者属性的唯一属性不能保证这一点)。

It seems to me Nibernate should have enough mapping metadata to do the right thing (or does the unique attribute on the property not ensure this?). Does anyone know how to do this or have a workaround?

感谢,

Martijn

推荐答案

您需要将一个Country实例分配给Person实例的Country属性(而不仅仅是设置ID)。例如:

You need to assign a Country instance to the Country property of the Person instance (not just set the ID). Something like:

Person p = new Person();
p.Country = session.Load<Country>(countryId);
session.Save(p);

然后NHibernate会知道该怎么办。这也不会导致DB命中检索国家,因为Load方法将返回一个国家代理,唯一你正在访问的是国家实例的ID。

Then NHibernate will know what to do. This will also not cause a DB hit to retrieve country, since the Load method will return a Country proxy and the only thing you're accessing is the Country instance's ID.

这篇关于NHibernate多对一和唯一约束违反的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆