【发布时间】:2011-02-01 07:25:21
【问题描述】:
我正在使用 ASP.NET MVC + NHibernate + Fluent NHibernate 并且遇到延迟加载问题。
通过这个问题 (How to fix a NHibernate lazy loading error "no session or session was closed"?),我发现我必须实现 Open Session in View 模式,但我不知道如何。
在我的存储库类中,我使用这样的方法
public ImageGallery GetById(int id) {
using(ISession session = NHibernateSessionFactory.OpenSession()) {
return session.Get<ImageGallery>(id);
}
}
public void Add(ImageGallery imageGallery) {
using(ISession session = NHibernateSessionFactory.OpenSession()) {
using(ITransaction transaction = session.BeginTransaction()) {
session.Save(imageGallery);
transaction.Commit();
}
}
}
这是我的会话工厂助手类:
public class NHibernateSessionFactory {
private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory {
get {
if(_sessionFactory == null) {
_sessionFactory = Fluently.Configure()
.Database(MySQLConfiguration.Standard.ConnectionString(MyConnString))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<ImageGalleryMap>())
.ExposeConfiguration(c => c.Properties.Add("hbm2ddl.keywords", "none"))
.BuildSessionFactory();
}
return _sessionFactory;
}
}
public static ISession OpenSession() {
return SessionFactory.OpenSession();
}
}
有人可以帮我实现 Open Session in View 模式吗?
谢谢。
【问题讨论】:
标签: asp.net-mvc nhibernate design-patterns fluent-nhibernate