剑花 烟雨

   江南  好 风景旧曾谙 日出江花红胜火 春来江水绿如蓝 能不忆东北

理想中的建筑师应该是一个诗人、数学家、精通历史、精通心理学、熟悉音乐、了解医学、还要具备天文学和计算的基本知识。
                                                                                                                         ------------------公元前25年,罗马建筑学家Vitruvius
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

NHibernate中CodeSmith的使用

Posted on 2007-06-02 14:46  落花人独立  阅读(3682)  评论(1编辑  收藏  举报

  在我们使用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

public class Accessory
    
{
        
Member Variables

*.hbm.xml

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

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

public class Accessory
    
{
        
Member Variables

*.hbm.xml

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

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

<property name="Id" type="Int64" update="false" insert="false">
            
<column name="id" length="8" sql-type="bigint" not-null="true"/>
        
</property>

就不会有异常出现了。

count hit
欢迎您到紫阁阳光坐客