今天开始用Nhibernate做为自己的ORM,但是做的过程中确实遇到了好多问题,现在将问题收集起来以防日后出现相同的问题,
总结下:
这就是我的整个项目,现在配置下hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!--
This template was written to work with NHibernate.Test.
Copy the template to your NHibernate.Test project folder and rename it in hibernate.cfg.xml and change it
for your own use before compile tests in VisualStudio.
-->
<!-- This is the System.Data.dll provider for SQL Server -->
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="NHibernate.Test">
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">
server=127.0.0.1;database=Subject;uid=sa;pwd=zhangwei
</property>
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
</session-factory>
</hibernate-configuration>
现在新建User.cs类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Subject.Model
{
/// <summary>
/// 用户表
/// </summary>
public class User
{
/// <summary>
/// 用户id
/// </summary>
public string Id { get; set; }
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 密码
/// </summary>
public string Password { get; set; }
/// <summary>
/// 性别
/// </summary>
public string Sex { get; set; }
/// <summary>
/// 个人简介
/// </summary>
public string BriefIntroduction { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime? CreateDt { get; set; }
}
}
现在映射这个User.cs类,新建User.hbm.xml文件并且进行配置,如下:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="Subject.Model" assembly="Subject.Model">
<class name="Subject.Model.User" table="User" lazy="false">
<id name="Id">
<column name="Id" sql-type="varchar(40)" not-null="true"/>
<generator class="uuid.hex" />
</id>
<property name="Name">
<column name="Name" sql-type="varchar(20)" not-null="false" />
</property>
<property name="Password">
<column name="Password" sql-type="varchar(20)" not-null="false" />
</property>
<property name="Sex">
<column name="Sex" sql-type="varchar(2)" not-null="false" />
</property>
<property name="BriefIntroduction">
<column name="BriefIntroduction" sql-type="varchar(500)" not-null="false" />
</property>
<property name="CreateDt">
<column name="CreateDt" sql-type="datetime" not-null="false" />
</property>
</class>
</hibernate-mapping>
注意设置User.hbm.xml文件属性,XML文件的默认生成操作为“内容”,这里需要修改为“嵌入的资源”,
然后测试:
public IList<User> Get()
{
try
{
return _session.CreateQuery("from Subject.Model.User").List<User>();
}
catch (Exception e)
{
throw;
}
}
发现数据为空,如图:
不可能啊?因为数据库里有数据啊,如图:
这是怎么回事,找了好久,终于被我找到问题的所在,如图:
原来要加这个,但是运行之后又出现了问题,唉,写个NHibernate出现这么多问题,自己跟自己说:淡定!
你猜是什么问题?原来Sqlserver2008系统表里有User表,你再建这个表就会有歧义,当然就会出现问题了,
所以我把User表改成Users表就OK了!
终于成功了,不容易啊!