这是我第一次使用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()
该表存在于数据库中,有什么问题?
由于
答案 0 :(得分:0)
表示变量_sessionFactory
为null
。您应该使用属性SessionFactory
代替它,它也会初始化_sessionFactory
变量。
session = SessionFactory.OpenSession();