配置(持久層)nhibernate期間,我收到一個異常。消息說,nhibernate找不到配置文件hibernate.cfg.xml
。但我欺騙了我的文件,並將其設置爲始終複製到輸出。我在單獨的程序集中存儲映射和持久類。但是控制檯項目和類庫項目都在其outpt文件夾中有配置文件。nhibernate配置拋出異常
配置文件
<?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();
}
}
幫助!
正如我之前說的選項已經設定。構建操作:內容。複製到輸出:始終複製。所有映射都被視爲嵌入式資源。也許我得到了某種錯字,但我看不到它。 – lexeme
確實。對不起,我沒有注意到。 –
沒關係。沒關係。 – lexeme