nhibernate - currentsessioncontext fluent nhibernate 怎么做呢?

标签 nhibernate fluent-nhibernate

我正在尝试对每个请求使用 fluent session 。我正在遵循 nhibernate 食谱中的“食谱”,但是它使用了 nhibernate 配置文件。

我不确定什么更好,但现在我坚持使用 fluent 配置只是因为我不知道如何设置 nhibernate 配置文件以使用 fluent 映射和 vanilla nhibernate 映射(hbm 文件)。

namespace Demo.WebUI
{
    public class MvcApplication : NinjectHttpApplication
    {
        public static ISessionFactory SessionFactory { get; private set; }

        protected override void OnApplicationStarted()
        {
            SessionFactory = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008.ConnectionString(
                    c => c.FromConnectionStringWithKey("test")))
                .Mappings(m => m.FluentMappings
                    .AddFromAssemblyOf
                     <Demo.Framework.Data.NhibernateMapping.UserMap>())
                .ExposeConfiguration(BuidSchema)
                .BuildSessionFactory();
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            var session = SessionFactory.OpenSession();
            //CurrentSessionContext.Bind(session);
        }

        protected void Application_EndRequest(object sender, EventArgs e)
        {
            //var session = CurrentSessionContext.Unbind(SessionFactory);
            SessionFactory.Dispose();
        }
    }
}

正如你在 Begin_Request 中看到的,书籍教程有
CurrentSessionContext.Bind(session);

但是,如果我使用它会引发错误,因为我没有使用 nhibernate 配置文件。

那么如何更改它以使用流畅的配置?或者我什至不需要做这一步?(即它是在内部完成的吗?)

最佳答案

您需要告诉 NHibernate 如何处理 session 上下文。以下可能有效:

Fluently.Configure()
        ...
        .ExposeConfiguration(cfg => cfg.SetProperty(
                                        Environment.CurrentSessionContextClass,
                                        "web")

此外,与此无关:您正在 EndRequest 上处理 SessionFactory。那是一个错误。

关于nhibernate - currentsessioncontext fluent nhibernate 怎么做呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4702703/

相关文章:

c# - Fluent NHibernate - 一对至多 (1 – 0..1) 关系

sqlite - 使用 SQLite In Memory 配置测试 NHibernate 时,如何创建另一个数据库?

c# - 如何限制 NHibernate 的 GetByCriteria 拉回的结果集?

c# - 为什么 Trim() 在这个表达式中失败?

NHibernate 性能插入

NHibernate 还是 Fluent NHibernate?

nhibernate - 使用 FluentNHibernate 映射通用 EntityBase<TEntity> 类

nhibernate - 如何在查询中跳过二级缓存?

nhibernate - 如何在 NHibernate 中使用不可为空的索引创建列表集合?

c# - 两个表的 Fluent Nhibernate 映射一对多在映射中使用唯一而不是主键