0

我有一个可以在运行 Nhibernate 2.1.0.4000 的 .Net 3.5 上运行的网站。我们使用 spring 作为我们的 ProxyFactory。

一切正常。我尝试使用向导将项目升级到 .Net 4.0。一切都很顺利。

但是一旦代码尝试对 Nhibernate 做任何事情,我就会得到一个非常不友好的 System.ExecutionEngineException 异常。没有堆栈跟踪,也没有内部异常。

我们正在使用 NhibernateHelper 类(如下),我已经使用它并且会话配置正常(没有例外)。与 .net 3.5 版本相比,细节没有任何变化

从数据库中获取某些东西的第一次尝试失败了

会话在请求开始时在处理程序中打开(下面未显示)。我们还使用在应用程序启动时设置的统一(不确定是否有任何影响)

第一次调用 Nhibernate 是

var emp = NHibernateHelper.CurrentSession.Get<SMS.DomainModel.Employee>(-200694);

我只想要一条错误消息,它意味着某些东西并给我一些继续下去的东西。

我试过查看 NhibernateProfiler 并且注册的所有内容都是会话的开始。

任何帮助深表感谢

NhibernateHelper 类如下

using System;
using System.Configuration;
using System.IO;
using System.Reflection;
using FluentNHibernate;
using FluentNHibernate.Cfg;
using HibernatingRhinos.NHibernate.Profiler.Appender;
using log4net;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data.Configuration;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Event;
using NHibernate.Tool.hbm2ddl;
using SMS.Infrastructure.Persistence.Logging;
using SMS.Infrastructure.Persistence.Mappings;
using Configuration=NHibernate.Cfg.Configuration;
using System.Data.SqlClient;

namespace SMS.Infrastructure.Persistence
{
    public static class NHibernateHelper
    {
        static readonly ILog Log = LogManager.GetLogger(typeof(NHibernateHelper));
        static Configuration configuration;

        public static ISessionFactory SessionFactory
        {
            get
            {
                return Singleton.sessionFactory;
            }
        }

        // Lazy singleton pattern from http://www.yoda.arachsys.com/csharp/singleton.html
        class Singleton
        {
            static Singleton() { }

            internal static readonly ISessionFactory sessionFactory = CreateSessionFactory();
        }

        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }

        public static ISession CurrentSession
        {
            get { return SessionFactory.GetCurrentSession(); }
        }

        static ISessionFactory CreateSessionFactory()
        {
            try
            {

                Log.Info("Creating NHibernate session factory");

                NHibernateProfiler.Initialize();

                configuration = new Configuration();

                try
                {
                    // Try to configure NHibernate automagically...
                    configuration.Configure();
                }
                catch (HibernateConfigException e)
                {
                    if (e.InnerException is IOException)
                    {
                        // Otherwise specify a file name manually.
                        configuration.Configure("hibernate.cfg.xml");
                    }
                    else
                        throw;
                }

                Log.Info("Registering custom SMS event listeners");

                RegisterCustomListeners(configuration);

                // Has someone specified a default_schema? No? try and guess
                // it from the (Enterprise Library :/ ) query string.
                if (!configuration.Properties.ContainsKey("default_schema"))
                {
                    Log.Info("Setting default schema");
                    configuration.SetProperty("default_schema", GetDefaultSchema());
                }

                ISessionFactory sessionFactory = Fluently.Configure(configuration)
                    .Mappings(m =>
                    {
                        m.HbmMappings.AddFromAssemblyOf<BusinessUnitTypeMapping>();
                        m.FluentMappings.AddFromAssemblyOf<BusinessUnitTypeMapping>();

                    })
                    .BuildSessionFactory();

                Log.Info("Session factory was configured successfully");

                return sessionFactory;
            }
            catch (Exception ex)
            {
                throw new ArgumentNullException(ex.ToString());
            }
        }

        /// <summary>
        /// NHibernate allows custom event listeners to be registered in 
        /// config files or programmatically. Due to the re-use of configs in
        /// SMS, we chose to do it via code.
        /// 
        /// This is how we extend NHibernate for SMS, and this is why
        /// NHibernate is the best ORM..!
        /// </summary>
        static void RegisterCustomListeners(Configuration config)
        {
            if (config == null)
                throw new ArgumentNullException("config");

            // Event listeners for audit logging.
            //config.SetListener(ListenerType.PreInsert, new AuditEventListener());
            //config.SetListener(ListenerType.PreUpdate, new AuditEventListener());
            //config.SetListener(ListenerType.PreDelete, new AuditEventListener());

            // Event listener for wiring up .NET events between parent/child
            // objects, and the intermediary mapping for Tasks.
            //
            // Warning: be careful with the order in which these listeners are
            // added!!!
            //
            // BindEventsOnLoadListener must come before 
            // TaskAddresseeLoadEventListener for example otherwise OSM Task
            // Decorators don't attach properly.
            config.SetListeners(ListenerType.PostLoad, new IPostLoadEventListener[]
                {
                    new BindEventsOnLoadListener(),
                    new TaskAddresseeLoadEventListener()
                });

        }

        /// <summary>
        /// Optional step: destroy and re-create the database scheme based on
        /// the mapping files. Gives you a totally clean database in between
        /// testing each fixture.
        /// </summary>
        public static void ExportDatabaseSchema(string fileName)
        {
            if (configuration == null)
                CreateSessionFactory();

            Log.InfoFormat("Exporting DDL to {0}", fileName);

            var exporter = new SchemaExport(configuration);
            exporter.SetOutputFile(fileName);
            exporter.Execute(true, false, false);
        }

        public static void ExportFluentMappings(string directoryName)
        {
            Log.InfoFormat("Exporting fluent mappings to {0}", directoryName);
            var model = new PersistenceModel();
            model.AddMappingsFromAssembly(Assembly.GetAssembly(typeof(BusinessUnitTypeMapping)));
            model.WriteMappingsTo(directoryName);
        }

        /// <summary>
        /// hibernate's default_schema is worked out programmatically from the
        /// Enterprise Library connection string. E.g.  
        /// Initial Catalog=OSM2Tests  -->  default_schema = SMS2Tests.dbo
        /// </summary>
        public static string GetDefaultSchema()
        {
            try
            {
                DatabaseSettings settings = DatabaseSettings.GetDatabaseSettings(new SystemConfigurationSource());
                var connectionstring = ConfigurationManager.ConnectionStrings[settings.DefaultDatabase].ConnectionString;
                var initialCatalog = new SqlConnectionStringBuilder(connectionstring).InitialCatalog;
                return String.Format("{0}.dbo", initialCatalog);
            }
            catch (Exception)
            {
                throw new Exception("Could not get default schema from connection string.");
            }
        }
    }
}
4

1 回答 1

2

通过删除对 NHProf 的引用,我能够解决类似的问题。

于 2011-05-29T23:36:22.967 回答