Bla*_*man 7 c# nhibernate asp.net-mvc fluent-nhibernate
我遵循了这个教程:http://nhforge.org/blogs/nhibernate/archive/2011/03/03/effective-nhibernate-session-management-for-web-apps.aspx
在尝试加载页面时,我没有收到"没有绑定到当前上下文的会话"错误(mvc 3).
public static ISessionFactory BuildSessionFactory()
{
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008 //
.ConnectionString(@"Server=.\SQLExpress;Database=db1;Uid=dev;Pwd=123;")
.ShowSql())
//.ExposeConfiguration(c => c.SetProperty("current_session_context_class", "web"))
//.CurrentSessionContext<CallSessionContext>()
.Mappings(m => m.FluentMappings
.AddFromAssemblyOf<User>())
.ExposeConfiguration(cfg => new SchemaExport(cfg)
.Create(false, false))
.BuildSessionFactory();
}
Run Code Online (Sandbox Code Playgroud)
实际错误在我的Repository.cs文件中:
第114行:public virtual T Get(int id)第115行:{第116行:return _sessionFactory.GetCurrentSession().Get(id); 第117行:}第118行:
当我调试它时,_sessionFactory不是null或任何东西,它似乎无法找到绑定的会话.
我在我的web.config中连接了httpmodule,它确实运行,所以这不是问题.
在我的nhibernate配置中,我尝试了两种方法:
.ExposeConfiguration(c => c.SetProperty("current_session_context_class", "web"))
Run Code Online (Sandbox Code Playgroud)
和
.CurrentSessionContext<CallSessionContext>()
Run Code Online (Sandbox Code Playgroud)
但那没用.
听起来您没有将会话绑定到上下文.请看下面的示例:
public class SessionFactory
{
protected static ISessionFactory sessionFactory;
private static ILog log = LogManager.GetLogger(typeof(SessionFactory));
//Several functions omitted for brevity
public static ISession GetCurrentSession()
{
if(!CurrentSessionContext.HasBind(GetSessionFactory()))
CurrentSessionContext.Bind(GetSessionFactory().OpenSession());
return GetSessionFactory().GetCurrentSession();
}
public static void DisposeCurrentSession()
{
ISession currentSession = CurrentSessionContext.Unbind(GetSessionFactory());
currentSession.Close();
currentSession.Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
上述的关键是,每当您检索第一个会话时,都会将其绑定到您正在使用的任何上下文.
| 归档时间: |
|
| 查看次数: |
10480 次 |
| 最近记录: |