您的位置:首页 > 其它

[转]NHibernate配置方法

2009-07-09 15:13 99 查看
使用NHibernate2.0.1版本. VS2008,数据库是SQL Server 2005.

1:在web.config,App.config里面配置

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!-- Add this element -->
<configSections>
<section
name="hibernate-configuration"
type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"
/>
</configSections>
<!-- Add this element -->
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.connection_string">Server=.\SQLEXPRESS;initial catalog=Test;Integrated Security=true</property>
</session-factory>
</hibernate-configuration>
<!-- Leave the system.web section unchanged -->
<system.web>
</system.web>
</configuration>
则需要这样实例化Configuration对象。
NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
这种配置方法将会到应用程序配置文件(App.Config,Web.Config)中查找NHibernate的配置信息.

2:hibernate.cfg.xml
建立名为hibernate.cfg.xml的文件。实例化Configuration config = new Configuration().Configure();这样NHibernate将会在目录下寻找hibernate.cfg.xml的配置文件。
hibernate.cfg.xml的格式
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="MySessionFactory">
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.connection_string">Server=TLSZ207\SQLEXPRESS;initial catalog=Test;Integrated Security=true</property>
</session-factory>
</hibernate-configuration>

指明配置文件
Configuration config = new Configuration().Configure(configFileName);
这种配置方法将查找指定的Hibernate标准配置文件,可以是绝对路径或者相对路径。还可以通过编码的方式来添加配置信息:
IDictionary props = new Hashtable();
props[“dialect”] = "NHibernate.Dialect.MsSql2005Dialect";
...
Configuration cfg = new Configuration();
cfg.Properties = props;//cfg.AddProperties(props);

VS2008里面NHibernate的智能感应:

在NHibernate的源代码项目中,在src\NHibernate这个目录下,把nhibernate-mapping.xsd,nhibernate-configuration.xsd,nhibernate-generic.xsd拷贝到: 安装目录的Microsoft Visual Studio 9.0\Xml\Schemas下面.这样,在进行NHibernate的配置时候就可以有提示了.

PS:使用的时候,发现个奇怪的问题.问题如下:

代码:

_session.CreateQuery("FROM Users").List<Users>();

会报:in expected: <end-of-text> (possibly an invalid or unmapped class name was used in the query 这个样的异常.

在网上找解决方法,发现有很多人都是这样问题.有人说把users.hbm.xml改成"嵌入的资源"就可以了.但是,实际根本不行,我的映射文件本来就是设置的是""嵌入的资源".

如果使用以下代码:

ICriteria critera=_session.CreateCriteria(typeof(Users));

critera.List();

这样写就是对的.

真不晓得是怎么搞的!

本文转自:http://blog.csdn.net/canduecho/archive/2009/04/13/4070954.aspx ,其中部分做了修改.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: