.hbm.xml文件中唯一不引发异常 [英] unique in .hbm.xml file not raising exception

查看:85
本文介绍了.hbm.xml文件中唯一不引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.hbm.xml文件中包含以下内容

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();
            }    
        }

推荐答案

仅当如果您要检查NHibernate的唯一性,那就是数据验证,您应该查看

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.

您还可以检查 natural-id 元素.

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.

这篇关于.hbm.xml文件中唯一不引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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