Creating a transaction ASP.NET MVC action filter

We can extend the concepts of the previous recipe to NHibernate transactions as well. In this recipe, we'll show you how to create an action filter to manage our NHibernate sessions and transactions in an MVC or Web API 2 application.

Getting ready

Complete the previous recipe, Creating a session ASP.NET MVC action filter.

How to do it…

  1. Add the NeedsPersistenceAttribute class:
    public class NeedsPersistenceAttribute : NHibernateSessionAttribute { protected ISession session { get { return sessionFactory.GetCurrentSession(); } } public override void OnActionExecuting( ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); session.BeginTransaction(); } public override void OnActionExecuted( ...

Get NHibernate 4.x Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.