龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > asp.net编程 >

NHibernate数据库映射教程:1、NHibernate实例入门

时间:2009-12-21 11:47来源:未知 作者:admin 点击:
分享到:
NHibernate 是一个面向.NET 环境 的对象/关系数据库映射工具。对象 关系映射(O/R Mapping,Object Relational Mapping)表示一种技术 ,用来把对象模型表示的对象映射到 基于SQL 的关系模型数据结构

NHibernate 是一个面向.NET 环境 的对象/关系数据库映射工具。对象 关系映射(O/R Mapping,Object Relational Mapping)表示一种技术 ,用来把对象模型表示的对象映射到 基于SQL 的关系模型数据结构中去。

在网上看对NHibernate评价很不错,比Linq好,所以整理一系列教程。

先来看下入门实例:

环境为:vs2008+win2003 server+mssql2000 +.net 3.5

(一)  数据库

这里我用的还是SelfTest数据库。新加的Customer客户表

Customer表结构如下:(version字段用于并发处理的,请参见http://www.cnblogs.com/lyj/archive/2008/10/21/1316269.html

 

(二)  新建空解决方案,并新建类库项目

解决方案:NHBSample

在解决方案中添加两个类库

(1)       Shared类库,用于存放要引入的库文件(方便于管理与引用)

(2)       SelfTest类库,这个类库包含所有的数据(包括测试)

解决方案图示如下:

 

(三)  添加实体类Customer

在SelfTest2类库中添加Customer类

public class Customer

    {

        public virtual int Unid { get; set; }

        public virtual string FirstName { get; set; }

        public virtual string LastName { get; set; }

}

注意:这里属性要为virtual。就会出否则出现无效的代理类型异常。

现在把Unid的虚修饰符去掉,这里我在vs打印窗口找了一段信息如下:

……

InvalidProxyTypeException : The following types may not be used as proxies:

SelfTest2.Customer: method get_Unid should be 'public/protected virtual' or 'protected internal virtual'

SelfTest2.Customer: method set_Unid should be 'public/protected virtual' or 'protected internal virtual'

……

 

(四)  添加实体类的Mapping(映射)

为Customer类添加映射。文件名也叫Customer(全名:Customer.hbm.xml)吧!

<?xml version="1.0" encoding="utf-8" ?>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="SelfTest2" namespace="SelfTest2">

  <class>

    <id column="CustomerId">

      <generator></generator>

    </id>

    <property column="firstname"></property>

    <property column="LastName"></property>

  </class>

</hibernate-mapping>

 

提示:

为了出现智能提示,可以把

configuration.xsd和nhibernate-mapping.xsd文件保存到vs环境

安装目录(我的是vs2008,就是9.0):

……\Microsoft Visual Studio 9.0\Xml\Schemas

注意:这里有几个要注意的地方

(1)         hibernate-mapping 这里assembly要添加,namespace也要添加。Assembly为dll文件名,namespace为实体类(Customer)的名字空间名。

如果不添加assembly名,则会出现映射异常,(程序集未指定)。如下信息:

NHibernate.MappingException : Could not compile the mapping document: SelfTest2.Customer.hbm.xml

  ----> NHibernate.MappingException : persistent class SelfTest2.Customer not found

  ----> System.TypeLoadException : Could not load type SelfTest2.Customer. Possible cause: no assembly name specified.

如果不指定名字空间名则也会出现映射异常,(不能加载实体类),如下信息:

NHibernate.MappingException : Could not compile the mapping document: SelfTest2.Customer.hbm.xml

  ----> NHibernate.MappingException : persistent class Customer, SelfTest2 not found

  ----> System.TypeLoadException : 未能从程序集“SelfTest2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”中加载类型“Customer”。

 

(2)         类的属性名要与Customer实体类中的名字相同(敏感),列名不敏感


精彩图集

赞助商链接