ASP.NET MVC中的telerik OpenAccess NULL引用

时间:2015-05-18 04:39:34

标签: c# asp.net-mvc telerik telerik-open-access openaccess

我使用Telerik Domain Model for ASP.NET MVC 5.当我在Unit测试项目中使用上下文时,一切都运行得很好。但是当我在MVC控制器上使用它时,我得到了这个例外:

a = [(1, 'Pencil', '99', 25.0, 30.0, 5.0), (2, 'Marker', '40', 30.0, 20.0, -10.0)]

a_new = [tuple(map(str, i)) for i in a]

>>> print(a_new)
[('1', 'Pencil', '99', '25.0', '30.0', '5.0'), ('2', 'Marker', '40', '30.0', '20.0', '-10.0')]

感谢

1 个答案:

答案 0 :(得分:0)

经过多次试错后我找到了这个解决方案

public class MyController : Controller
{
    private EntitiesModel _dbContext;
    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
        base.Initialize(requestContext);
        this._dbContext = ContextFactory.GetContextPerRequest();

        //the problem is disappeared after add this line
        var obj = this._dbContext.AnyTable.FirstOrDefault(); 
    }

    public ActionResult Index()
    {
        var q = _dbContext.AnyTable.ToList();
        return View(q); //Now It works like charm
    }
}

public class ContextFactory
{
    private static readonly string ContextKey = typeof(EntitiesModel).FullName;
    public static EntitiesModel GetContextPerRequest()
    {
        var httpContext = HttpContext.Current;
        if (httpContext == null)
        {
            return new EntitiesModel();
        }
        var context = httpContext.Items[ContextKey] as EntitiesModel;
        if (context != null) return context;
        context = new EntitiesModel();
        httpContext.Items[ContextKey] = context;
        return context;
    }
}

我必须在Initialize之后查询数据库,否则我将得到Null引用错误。如果有人有更好的解决方案或解释,我会很高兴知道。感谢