Inheriting LINQ-to-SQL data context from base controller

瘦欲@ 提交于 2020-01-02 05:04:31

问题


My base controller class, BaseController, is inherited by public-facing controllers to access a shared data context between requests with LINQ-to-SQL.

  • Am I accessing my data context in an efficient and safe way by storing it in HttpContext.Current.Items for each HTTP request?

DataContextHelper class

internal static class DataContextHelper
{
    public static MyDataContext CurrentContext
    {
        get
        {
            if (HttpContext.Current.Items["MyDataContext"] == null)
            {
                MyDataContext context = new MyDataContext();
                HttpContext.Current.Items["MyDataContext"] = context;
            }
            return (MyDataContext)HttpContext.Current.Items["MyDataContext"];
        }
    }
}

BaseController class:

public class BaseController : Controller
{
    protected MyDataContext db
    {
        get {
            return DataContextHelper.CurrentContext;
        }
    }
}

HomeController class:

[HandleError]
public class HomeController : BaseController // inherits db member
{
    public ActionResult SomeAction(string id)
    {
        User user = db.Users.First(u => u.UserId == id);
        // ... do stuff
        db.SubmitChanges();
    }
}

回答1:


Yes, this is a common pattern with all the major ORMs with both WebForms and MVC.

The only thing I would add a explicit dispose after each controller action is executed. just to make sure everything is disposed of correctly.

In BaseController.cs:

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (HttpContext.Current.Items["MyDataContext"] == null)
            return;

        var context = (MyDataContext)HttpContext.Current.Items["MyDataContext"];

        context.Dispose();
    }


来源:https://stackoverflow.com/questions/2684551/inheriting-linq-to-sql-data-context-from-base-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!