.hbm.xml 文件中唯一,不会引发异常
我的 .hbm.xml 文件中有以下内容
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="Core.Domain.Model"
assembly="Core">
<class name="Category" table="Categories" dynamic-update="true">
<cache usage="read-write"/>
<id name="Id" column="Id" type="Guid">
<generator class="guid"/>
</id>
<property name="Name" length="100">
<column name="Name" unique="true" index="IX_Category"/>
</property>
</class>
</hibernate-mapping>
我有以下代码,但是,我可以看到当我为“名称”字段插入重复值时没有引发异常。为什么会这样呢?
void IRepository<Category>.Save(Category entity)
{
using (var scope = new TransactionScope(TransactionScopeOption.Required))
{
using (ISession session = NHibernateHelper.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(entity);
transaction.Commit();
}
}
scope.Complete();
}
}
I am having the following in my .hbm.xml file
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="Core.Domain.Model"
assembly="Core">
<class name="Category" table="Categories" dynamic-update="true">
<cache usage="read-write"/>
<id name="Id" column="Id" type="Guid">
<generator class="guid"/>
</id>
<property name="Name" length="100">
<column name="Name" unique="true" index="IX_Category"/>
</property>
</class>
</hibernate-mapping>
I am having the following code, however, I can see that no exception is being raised when I am inserting a duplicate value for the Name field. Why is that so?
void IRepository<Category>.Save(Category entity)
{
using (var scope = new TransactionScope(TransactionScopeOption.Required))
{
using (ISession session = NHibernateHelper.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(entity);
transaction.Commit();
}
}
scope.Complete();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
unique属性仅在生成来自映射的 DDL 架构 (hbm)。
如果您想使用 NHibernate 检查唯一性,那就是数据验证,您应该查看 NHibernate 验证器。
正如拉斐尔所说,你必须编写自己的验证器。
您还可以检查natural-id 元素。
除非您绝对需要在应用程序端验证唯一性,否则此示例 和这个让我觉得让数据库来做这项工作可能会更好。
The unique attribute is only used when generating a DDL schema from a mapping (hbm).
If you want to check uniqueness with NHibernate, it is data validation and you should look NHibernate validator.
And as Rafael said you have to write your own validator.
You can also check the natural-id element.
Unless you absolutely need to validate uniqueness on application side, this sample and this one make me think it may be better to let the database do this job.
NHibernate 是否为您生成了数据库架构?因为即使您将属性设置为
unique
,如果架构没有unique
约束,它也不会执行任何操作。基本上,该属性不会查询数据库来寻找唯一性;它只会在上设置 SQL 约束插入
。Did NHibernate generate the database schema for you? Because even though you set the property as
unique
, if the schema does not have theunique
constraint, it will do nothing. Basically, that property won't query the database looking for uniqueness; it will only set the SQL constraint oninsert
.