最も簡単な方法は、ベースコントローラーに実装OnActionExecuting
して使用することです。OnActionExecuted
次のように作成するとしますRavenController
。
public class RavenController : Controller
{
public IDocumentSession Session { get; set; }
protected IDocumentStore _documentStore;
public RavenController(IDocumentStore documentStore)
{
_documentStore = documentStore;
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
Session = _documentStore.OpenSession();
base.OnActionExecuting(filterContext);
}
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
using (Session)
{
if (Session != null && filterContext.Exception == null)
{
Session.SaveChanges();
}
}
base.OnActionExecuted(filterContext);
}
}
次に、独自のコントローラーで行う必要があるのは、次のRavenController
ように継承することだけです。
public class HomeController : RavenController
{
public HomeController(IDocumentStore store)
: base(store)
{
}
public ActionResult CreateUser(UserModel model)
{
if (ModelState.IsValid)
{
User user = Session.Load<User>(model.email);
if (user == null) {
// no user found, let's create it
Session.Store(model);
}
else {
ModelState.AddModelError("", "That email already exists.");
}
}
return View(model);
}
}
興味深いことに、まさにこの手法を示すブログ投稿を見つけました...
それは私がしたことよりもずっと多くを説明しています。それがあなたのより良い助けになることを願っています
RavenDB をバッキング ストアとして使用して ASP.NET MVC アプリを構築する