在我们使用NHibernate进行软件开发的时候,最初的例子会告诉我们用CodeSmith来生成Mapping,但是没有告诉你是按什么规则生成的,在使用的过程中你会发现根据不同的情况会有不同的问题出现。出现这些问题的原因就是CodeSmith中的NHibernate Template生成的代码是按默认的值生成的,当你的系统在全盘不是默认的值的时候就要根据情况做不同的配置。这些都在NHibernate的相应的文档中有提到,只是一不小心就忽略过去了,在网上搜索来的中文的帖子,可读性都很强,但是技术的细节做的不够,总是忽略了初学入门的时候那种懵懵懂懂的状态。既然是我们是为了让别人少走些弯路,那就要做的细些,不要做什么做了一半,觉得这也简单,那也简单,小问题也会影响大结果。所以在写文档的时候,无所不细,无所不到,就当我们什么也不会吧;)
  现在还是回过头来说CodeSmith生成的代码。如果是你的数据库表格中的定义如下:

字段名 类型 长度 主键
Id bigint 8 not null
userid char 10 primary key not null
other varchar 50          not null

这个表在生成代码的时候会有很多的问题出现,其一会生成两个Id字段,在生成Dll的时候就通不过编译;其二,生成的*.hbm.xml中的Id值亦会有两个,但是关键字的生成也会有问题出现。生成的例子如下:
*.cs

NHibernate中CodeSmith的使用public class Accessory
}

*.hbm.xml

NHibernate中CodeSmith的使用<class name="OfficeSystem.Pmis.Entities.Accessory, OfficeSystem.Pmis.Entities" table="Accessories">
NHibernate中CodeSmith的使用        
<id name="Id" type="String" unsaved-value="null">
NHibernate中CodeSmith的使用            
<column name="userId" length="8" sql-type="char" not-null="true" unique="true" index="PK_Accessories"/>
NHibernate中CodeSmith的使用            
<generator class="native" />
NHibernate中CodeSmith的使用        
</id>
NHibernate中CodeSmith的使用        
<property name="Id" type="Int64">
NHibernate中CodeSmith的使用            
<column name="id" length="8" sql-type="bigint" not-null="true"/>
NHibernate中CodeSmith的使用        
</property>
NHibernate中CodeSmith的使用        
<property name="Other" type="String">
NHibernate中CodeSmith的使用            
<column name="other" length="50" sql-type="varchar" not-null="true"/>
NHibernate中CodeSmith的使用        
</property>

看到了么?有两个同名的Id值存在,在这个时候你就要手动的来改一下这两个文件,将相应的文件改成如下的形式:
*.cs

NHibernate中CodeSmith的使用public class Accessory
}

*.hbm.xml

NHibernate中CodeSmith的使用<class name="OfficeSystem.Pmis.Entities.Accessory, OfficeSystem.Pmis.Entities" table="Accessories">
NHibernate中CodeSmith的使用        
<id name="UserId" type="String" unsaved-value="null">
NHibernate中CodeSmith的使用            
<column name="userId" length="8" sql-type="char" not-null="true" unique="true" index="PK_Accessories"/>
NHibernate中CodeSmith的使用            
<generator class="assigned" />
NHibernate中CodeSmith的使用        
</id>
NHibernate中CodeSmith的使用        
<property name="Id" type="Int64">
NHibernate中CodeSmith的使用            
<column name="id" length="8" sql-type="bigint" not-null="true"/>
NHibernate中CodeSmith的使用        
</property>
NHibernate中CodeSmith的使用        
<property name="Other" type="String">
NHibernate中CodeSmith的使用            
<column name="other" length="50" sql-type="varchar" not-null="true"/>
NHibernate中CodeSmith的使用        
</property>

这样改过来就可以了。如果Id为Int64的那列在数据库更新异常的时候要改成

NHibernate中CodeSmith的使用<property name="Id" type="Int64" update="false" insert="false">
NHibernate中CodeSmith的使用            
<column name="id" length="8" sql-type="bigint" not-null="true"/>
NHibernate中CodeSmith的使用        
</property>
NHibernate中CodeSmith的使用

就不会有异常出现了。

相关文章: