带有 nHibernate 的 MVC3 Razor

发布于 2024-12-01 16:45:12 字数 3821 浏览 1 评论 0原文

作为一个著名的 ORM,我们决定使用 nHIbernate 和 asp.net mvc3。我们按照以下方式设置我们的项目:

  1. NHibernate Repository [包含 nhibernate 的映射、服务和存储库]
  2. MVC3 [这是一个 UI]
  3. Test MVC NHibernate [这是一个带有 NUnit 的测试项目]

在上面,[] 文本写为 ti明确层次。

一切工作正常,意味着映射、插入、更新、删除操作的所有单元测试都已通过。 不幸的是,当我们从 mvc3 应用程序执行相同的操作时,它会抛出以下错误:

   "An exception occurred during configuration of persistence layer."   

完整的堆栈跟踪如下:

   at NHibernate.Cfg.ConfigurationSchema.HibernateConfiguration..ctor(XmlReader hbConfigurationReader, Boolean fromAppSetting) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Cfg\ConfigurationSchema\HibernateConfiguration.cs:line 55
   at NHibernate.Cfg.ConfigurationSchema.HibernateConfiguration..ctor(XmlReader hbConfigurationReader) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Cfg\ConfigurationSchema\HibernateConfiguration.cs:line 36
   at NHibernate.Cfg.Configuration.Configure(XmlReader textReader) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Cfg\Configuration.cs:line 1511
   at NHibernate.Cfg.Configuration.Configure(String fileName, Boolean ignoreSessionFactoryConfig) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Cfg\Configuration.cs:line 1433
   at NHibernate.Cfg.Configuration.Configure(String fileName) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Cfg\Configuration.cs:line 1418
   at NHibernate.Cfg.Configuration.Configure() in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Cfg\Configuration.cs:line 1404
   at examplemvcapp.NHibernateRepository..ctor() in D:\example\examplemvcapp-NHExample\examplemvcapp\NHibernateRepository.cs:line 33
   at examplemvcapp_NHExample.UI.Models.CreateAppraisalModel..ctor() in D:\example\examplemvcapp-NHExample\examplemvcapp-NHExample.UI\Models\Department.cs:line 70  

请注意,MVC3 应用程序中的 NHIbernate 的所有配置设置与测试项目中的相同。

以下是我们遇到异常的人:

using (var nhr = new NHibernateRepository())
{
    this.Departments = nhr.GetAll<Departments>().Select(x => new SelectListItem 
        {
            Text = x.Departmentdescription, Value = x.Id.ToString()
        });
}

上面将引发以下异常:

public NHibernateRepository()
{
    if (sessionFactory == null)
    {
        config = new Configuration();
        config.Configure();
        config.AddAssembly(typeof(NHibernateRepository).Assembly);
        sessionFactory = config.BuildSessionFactory();
    }
    Session = sessionFactory.OpenSession();
    transaction = Session.BeginTransaction();
    Rollback = false;
}

上面在测试项目中工作正常:

using (var nhr = new NHibernateRepository())
{
    var DeptList = nhr.GetAll<Departments>();
}

以下是放置在 NHibernateRepository 项目中的 hibernate.cfg.xml 文件:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">  
  <session-factory>
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <property name="connection.connection_string">Data Source=(local);Initial Catalog=myDatabaseName;Integrated Security=True</property>
    <property name="show_sql">true</property>
    <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
    <property name="cache.use_query_cache">false</property>
    <property name="adonet.batch_size">100</property>
    <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>

  </session-factory>
</hibernate-configuration>

除了上面这个项目之外拥有 NHibernate 所需的所有 dll。

在测试项目中,没有特殊的配置设置,只是我们添加了存储库项目的引用以及此项目及其工作正常所需的其他程序集。

MVC3应用程序项目中也保留了同样的内容。

在这方面的任何帮助都是非常值得赞赏的。

问候

As a famous ORM we decided to user nHIbernate with asp.net mvc3. We set up our project in the following way:

  1. NHibernate Repository [contains mappings, service and repositories for nhibernate]
  2. MVC3 [this is a UI]
  3. Test MVC NHibernate [this is a test project with NUnit]

In above, [] text are written ti make clear about the layers.

Everything is working fine, means all Unit Tests are passed for mapping, insert, update, delete operations.
Unfotunately, when we are doing the same operation from our mvc3 application then it threw following error:

   "An exception occurred during configuration of persistence layer."   

Full stack-trace is as follow:

   at NHibernate.Cfg.ConfigurationSchema.HibernateConfiguration..ctor(XmlReader hbConfigurationReader, Boolean fromAppSetting) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Cfg\ConfigurationSchema\HibernateConfiguration.cs:line 55
   at NHibernate.Cfg.ConfigurationSchema.HibernateConfiguration..ctor(XmlReader hbConfigurationReader) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Cfg\ConfigurationSchema\HibernateConfiguration.cs:line 36
   at NHibernate.Cfg.Configuration.Configure(XmlReader textReader) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Cfg\Configuration.cs:line 1511
   at NHibernate.Cfg.Configuration.Configure(String fileName, Boolean ignoreSessionFactoryConfig) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Cfg\Configuration.cs:line 1433
   at NHibernate.Cfg.Configuration.Configure(String fileName) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Cfg\Configuration.cs:line 1418
   at NHibernate.Cfg.Configuration.Configure() in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Cfg\Configuration.cs:line 1404
   at examplemvcapp.NHibernateRepository..ctor() in D:\example\examplemvcapp-NHExample\examplemvcapp\NHibernateRepository.cs:line 33
   at examplemvcapp_NHExample.UI.Models.CreateAppraisalModel..ctor() in D:\example\examplemvcapp-NHExample\examplemvcapp-NHExample.UI\Models\Department.cs:line 70  

Please note that all configuration settings for NHIbernate are same in MVC3 app as in Test project.

Following is the guy where we got the exception :

using (var nhr = new NHibernateRepository())
{
    this.Departments = nhr.GetAll<Departments>().Select(x => new SelectListItem 
        {
            Text = x.Departmentdescription, Value = x.Id.ToString()
        });
}

Above will bring up to following and threw an exception :

public NHibernateRepository()
{
    if (sessionFactory == null)
    {
        config = new Configuration();
        config.Configure();
        config.AddAssembly(typeof(NHibernateRepository).Assembly);
        sessionFactory = config.BuildSessionFactory();
    }
    Session = sessionFactory.OpenSession();
    transaction = Session.BeginTransaction();
    Rollback = false;
}

The above is working fine in Test project :

using (var nhr = new NHibernateRepository())
{
    var DeptList = nhr.GetAll<Departments>();
}

Following is the hibernate.cfg.xml file placed in NHibernateRepository project:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">  
  <session-factory>
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <property name="connection.connection_string">Data Source=(local);Initial Catalog=myDatabaseName;Integrated Security=True</property>
    <property name="show_sql">true</property>
    <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
    <property name="cache.use_query_cache">false</property>
    <property name="adonet.batch_size">100</property>
    <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>

  </session-factory>
</hibernate-configuration>

Apart from above this project is having all dlls required for NHibernate.

In Test project there is no special configuration settings just we add reference of Repository project and other assemblies required for this and its working fine.

The same has been maintained in MVC3 application project.

Any help in this regard is most appreciable.

Regards

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

许你一世情深 2024-12-08 16:45:12

我不确定这是否能解决您当前的问题,但我确实有一些建议。首先,在您的 Global.asax 中或(我的偏好)通过 HttpModule 实现每个请求的会话管理。这是一个简单的示例:

public class NHHttpModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.EndRequest += ApplicationEndRequest;
        context.BeginRequest += ApplicationBeginRequest;
    }

    public void ApplicationBeginRequest(object sender, EventArgs e)
    {
        CurrentSessionContext.Bind(SessionFactory.GetNewSession());
    }

    public void ApplicationEndRequest(object sender, EventArgs e)
    {
        var currentSession = CurrentSessionContext.Unbind(SessionFactory.GetSessionFactory());
        currentSession.Close();
        currentSession.Dispose();
    }

    public void Dispose()
    {
        // Do nothing
    }
}

请注意,这还会在请求管理期间绑定当前会话上下文。

另外,请确保您设置了正确的会话上下文。测试可能应该使用 thread 上下文,但 Web 应用程序应该使用 web 上下文。我个人通过 Fluent NHibernate 进行配置,但我相信在 XML 配置文件中它会显示为:

<property name="current_session_context_class">web</property>

同样,我通常使用 FNH 进行配置,因此请验证这一点。

I'm not sure if this will address your current issues, but I do have a few recommendations. First, implement session-per-request session management, either in your Global.asax or (my preference) via an HttpModule. Here's a simple example:

public class NHHttpModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.EndRequest += ApplicationEndRequest;
        context.BeginRequest += ApplicationBeginRequest;
    }

    public void ApplicationBeginRequest(object sender, EventArgs e)
    {
        CurrentSessionContext.Bind(SessionFactory.GetNewSession());
    }

    public void ApplicationEndRequest(object sender, EventArgs e)
    {
        var currentSession = CurrentSessionContext.Unbind(SessionFactory.GetSessionFactory());
        currentSession.Close();
        currentSession.Dispose();
    }

    public void Dispose()
    {
        // Do nothing
    }
}

Note that this also binds the current session context during the request management.

Also, ensure that you're setting the proper session context. Tests should probably use the thread context, but web applications should use the web context. I personally configure this via Fluent NHibernate, but I believe in the XML config files it would appear as:

<property name="current_session_context_class">web</property>

Again, I generally configure with FNH, so verify that.

谎言月老 2024-12-08 16:45:12

根据@Michael - 我通过提供以下答案来关闭此线程,这是我在研究过程中发现的。

为了获得正确的解决方案,我们需要做两件事;

  1. 如果使用 XML 文件,我们需要将它们设置为嵌入属性
  2. 如果不使用 xml 文件 - 我们需要进行编译设置

上面只需从解决方案资源管理器中选择文件名,然后按 F4 或通过右键单击文件名查看属性窗口,然后然后是属性链接。

谢谢大家 - 回答上述问题。

Per @Michael - I am closing this thread by supplying following answer, I have found during my reasearch.

There are two things we need to do for the proper solution;

  1. If using XML files we need to set them as Embedded in properties
  2. If not using xml files - we need to make the compiled

To set above just select file name from solution explorere and press F4 or See property window by Right clicking on the file name and then property link.

Thanks everyone - who answered for the above question.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文