ASP.NET MVC Transaction Attribute (using NHibernate) - Scott's Blog
NHibernateじゃなくても、以下のようなTransactionAttributeで。
using System;
using System.Transactions;
using System.Web.Mvc;
namespace MainSite.Controllers
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class TransactionAttribute : ActionFilterAttribute
{
private TransactionScope _transactionScope;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
_transactionScope = new TransactionScope();
base.OnActionExecuting(filterContext);
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
if (filterContext.Exception == null)
_transactionScope.Complete();
_transactionScope.Dispose();
}
}
}
適当なDataContextを用意してこれまた適当なAction(適当すぎてすいません)で。
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
[HttpPost,ActionName("Index")]
[Transaction]
public ActionResult IndexPost(string name)
{
var db = new DataClasses1DataContext();
db.Table1s.InsertOnSubmit(new Table1 {name = name});
db.SubmitChanges();
//throw new HttpException(500,"Error!");
return RedirectToAction("Index");
}
Unit of Workって言うんですかね~。Exception起こせばロールバックするんだけど...。トランザクションってこのレイヤで意識するものなのかな~。う~ん。好みや規模に合わせて好きなやり方でどうぞ、ってことで。