0

这是我第一次使用 NHibernate,我正在尝试使用 MVC 4 创建一个应用程序,这是我的配置文件:

<?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="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <property name="connection.connection_string">Data Source=.\SQLEXPRESS;Initial Catalog=loc;Persist Security Info=True;Trusted_Connection=Yes;Pooling=yes;connection lifetime=300;User Id=sa;Password=###</property>
    <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
    <property name="show_sql">false</property>

和映射文件:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="HelloWorldHib"
                   namespace="HelloWorldHib.Mappings">
  <class name="Product" table="Products">
    <id name="Id" column="Id">
      <generator class="native"></generator>
    </id>
    <property name="Name"></property>
    <property name="Category"></property>
    <property name="IsDis"></property>
  </class>
</hibernate-mapping>

和帮手:

public class NHibernateHelper
{
    private static ISessionFactory _sessionFactory;
    private static Configuration cfg;

    private static ISessionFactory SessionFactory
    {
        get
        {
            if (_sessionFactory == null)
            {
                cfg.Configure(HttpContext.Current.Server.MapPath("~/hibernate.cfg.xml"));
                cfg.AddDirectory(new System.IO.DirectoryInfo(HttpContext.Current.Server.MapPath(@"~/Mappings")));
                cfg.AddAssembly(typeof(Product).Assembly);
                _sessionFactory = cfg.BuildSessionFactory();

                if (_sessionFactory == null)
                    throw new InvalidOperationException("session factory could not be built");
            }
            return _sessionFactory;
        }
    }

    public static ISession OpenSession()
    {
        ISession session;

        session = _sessionFactory.OpenSession();
        if (session == null)
            throw new InvalidOperationException("session could not be opend");

        return session;
    }
}

当我运行我的应用程序时,我会Object reference not set to an instance of an object在这条线上session = _sessionFactory.OpenSession()

表存在于数据库中,有什么问题?

谢谢

4

1 回答 1

0

表示变量_sessionFactorynull。您应该使用该属性SessionFactory来初始化_sessionFactory变量。

session = SessionFactory.OpenSession();
于 2013-09-16T17:59:26.950 回答