【发布时间】:2011-11-04 22:22:09
【问题描述】:
在(持久层)nhibernate 的配置期间,我得到一个异常。消息说 nhibernate 找不到配置文件hibernate.cfg.xml。但我检查了我的文件,它设置为始终复制到输出。我将映射和持久类存储在单独的程序集中。但是控制台项目和类库项目在它们的 outpt 文件夹中都有配置文件。
配置文件
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">
NHibernate.Connection.DriverConnectionProvider
</property>
<property name="dialect">
NHibernate.Dialect.MsSql2008Dialect
</property>
<property name="connection.driver_class">
NHibernate.Driver.SqlClientDriver
</property>
<property name="connection.connection_string">
Data Source=(local); Initial Catalog=KrossThoughtDB;
Integrated Security=SSPI
</property>
<property name="show_sql">
true
</property>
<mapping resource="MyApp.Domain.Model.Entities.Mappings.User.hbm.xml" assembly="MyApp.Domain" />
<mapping resource="MyApp.Domain.Model.Entities.Mappings.Blog.hbm.xml" assembly="MyApp.Domain" />
<mapping resource="MyApp.Domain.Model.Entities.Mappings.Post.hbm.xml" assembly="MyApp.Domain" />
<mapping resource="MyApp.Domain.Model.Entities.Mappings.Category.hbm.xml" assembly="MyApp.Domain" />
<mapping resource="MyApp.Domain.Model.Entities.Mappings.Feedback.hbm.xml" assembly="MyApp.Domain" />
</session-factory>
</hibernate-configuration>
我还使用 NHibernate 官方文档中提供的 NHibernate 会话助手实现。
会话助手
public sealed class SessionHelper
{
private const String CurrentSessionKey = "nhibernate.current_session";
private static readonly ISessionFactory sessionFactory;
static SessionHelper()
{
sessionFactory = new Configuration().
Configure().
BuildSessionFactory();
}
public static ISession GetCurrentSession()
{
var context = HttpContext.Current;
var currentSession = context.Items[CurrentSessionKey] as ISession;
if(null == currentSession)
{
currentSession = sessionFactory.OpenSession();
context.Items[CurrentSessionKey] = currentSession;
}
return currentSession;
}
public static void CloseSession()
{
var context = HttpContext.Current;
var currentSession = context.Items[CurrentSessionKey] as ISession;
if(null == currentSession)
{
return;
}
currentSession.Close();
context.Items.Remove(CurrentSessionKey);
}
public static void CloseSessionFactory()
{
if(null != sessionFactory)
{
sessionFactory.Close();
}
}
}
然后我在示例控制台应用程序中调用此代码
客户端代码
private static void Main(String[] args)
{
// the next line exception's thrown
using(var session = SessionHelper.GetCurrentSession())
using(var tx = session.BeginTransaction())
{
// some actions...
tx.Commit();
}
}
救命!
【问题讨论】:
标签: c# nhibernate exception