Nhibernate开发专题博客

Nhibernate开发专题博客,为您精选Nhibernate开发教程,助您开发愉快!

公告信息
欢迎光临Nhibernate开发专题博客,祝您开发愉快!
文章档案

MVC3 Nhibernate声明式事务使用示例教程

在ASP.NET MVC3中使用NHibernate事务时,因为NHibernate不支持嵌套式事务操作,所以,我们可以利用MVC3来封装一下,下面给大伙发两个代码示例:

顺路推荐下国产的cyq.data 数据框架。

因为,所以ASP.NET MVC中通常使用一个事务来封装一次请求中的数据库操作。

下面是我认为比较漂亮的写法。

using System.Web.Mvc;
using NHibernate;

namespace WebMVC.Filters
{
    public class Transactional : ActionFilterAttribute
    {
        protected ISession _Session;

        public Transactional()
        {
            _Session = DependencyResolver.Current.GetService<ISession>();
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            _Session.BeginTransaction();
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (_Session == null || !_Session.Transaction.IsActive)
                return;

            if (filterContext.Exception != null)
                _Session.Transaction.Rollback();
            else
                _Session.Transaction.Commit();
        }
    }
}

使用起来很方便。

using System.Web.Mvc;
using WebMVC.Filters;

namespace WebMVC.Controllers
{
    public class CustomersController : Controller
    {
        protected ICustomersRepository _CustomersRepository;

        public CustomersController(ICustomersRepository customersRepository)
        {
            _CustomersRepository = customersRepository;
        }

        [Transactional]
        public ActionResult List()
        {
            return View(_CustomersRepository.FindAll());
        }
    }
}

希望您能看懂上面两个简单的代码,哈哈!!!
新浪微博粉丝精灵,刷粉丝、刷评论、刷转发、企业商家微博营销必备工具"

2011/9/30 14:48:21 | Nhibernate开发教程 | |

#1游客[注册][180.129.225.*]2014/4/9 18:27:42
DependencyResolver.Current.GetService<ISession>();这句为什么总是返回null
  • 发表评论