如何使用App.config中的NHibernate.Cfg.Configuration
将应用程序设置加载到System.Configuration.ConfigurationManager
对象?
答案 0 :(得分:23)
hibernate配置也可以移动到app.config中,这简化了启动代码。请参阅NHibernate参考手册中的XML Configuration File部分。
Configuration cfg = new NHibernate.Cfg.Configuration();
ISessionFactory sf = cfg.Configure().BuildSessionFactory();
在app.config中:
<configuration>
<configSections>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="connection.connection_string_name">Northwind</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
<mapping assembly="assemblyname" />
</session-factory>
</hibernate-configuration>
<connectionStrings>
<add name="Northwind" connectionString="Data Source=(local);Initial Catalog=Northwind;Trusted_Connection=True;>
</connectionStrings>
</configuration>
答案 1 :(得分:20)
的app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Northwind" connectionString=
"Data Source=(local);Initial Catalog=Northwind;Trusted_Connection=True;>
</connectionStrings>
</configuration>
C#代码:
string connectionString = System.Configuration.ConfigurationManager
.ConnectionStrings["Northwind"].ToString();
NHibernate.Cfg.Configuration nHibernateConfiguration =
new NHibernate.Cfg.Configuration();
nHibernateConfiguration.SetProperty(
NHibernate.Cfg.Environment.ProxyFactoryFactoryClass,
typeof(NHibernate.ByteCode.Castle.ProxyFactoryFactory).AssemblyQualifiedName);
nHibernateConfiguration.SetProperty(
NHibernate.Cfg.Environment.Dialect,
typeof(NHibernate.Dialect.MsSql2005Dialect).AssemblyQualifiedName);
nHibernateConfiguration.SetProperty(
NHibernate.Cfg.Environment.ConnectionString, connectionString);
nHibernateConfiguration.SetProperty(
NHibernate.Cfg.Environment.FormatSql, "true");
nHibernateConfiguration.AddAssembly(Assembly.GetCallingAssembly());
ISessionFactory oneISessionFactory = nHibernateConfiguration
.BuildSessionFactory();