【发布时间】:2012-09-12 07:51:27
【问题描述】:
我是 ASP.NET MVC3 的新手。当我在这些视频中做与这里相同的事情时,我遇到了这个错误:
(我在堆栈上查看了其他类似的问题,但没有找到解决方案)
我的代码是:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace testbaza.Controllers
{
public class KorController : Controller
{
private EntitiesModel dbContext;
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
if (this.Session[ContextModule.Content_KEY] != null)
{
this.dbContext = this.Session[ContextModule.Content_KEY] as EntitiesModel;
}
else {
throw new Telerik.OpenAccess.Exceptions.NoSuchObjectException("Cannot find EntitiesModel", null);
}
}
我收到此错误:名称“ContextModule”在当前上下文中不存在。
这是我之前做的进一步代码:
我在 project\Web.config 中添加了这个(与视频 1 相同):
<httpModules>
<add name="ContextModule" type="testbaza.ContextModule, testbaza"/>
</httpModules>
我将名为“ContextModule”的 ASP.NET 模块添加到 \project(与视频中相同)
这是 ContextModule.cs:
using System;
using System.Web;
namespace testbaza.Models
{
public class ContextModule : IHttpModule
{
internal const string CONTEXT_KEY = "datacontext";
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.PostRequestHandlerExecute += new EventHandler(context_PostRequestHandlerExecute);
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
}
private void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
if (HttpContext.Current.Session != null)
{
HttpContext.Current.Session[CONTEXT_KEY] = new EntitiesModel();
}
}
private void context_PostRequestHandlerExecute(object sender, EventArgs e)
{
CommitTransactions();
DisposeContext();
ClearSession();
}
private void CommitTransactions()
{
if (HttpContext.Current.Session == null)
{
return;
}
EntitiesModel dbContext =
HttpContext.Current.Session[CONTEXT_KEY] as EntitiesModel;
if (dbContext != null)
{
dbContext.SaveChanges();
}
}
private void DisposeContext()
{
if (HttpContext.Current.Session == null)
{
return;
}
EntitiesModel dbContext =
HttpContext.Current.Session[CONTEXT_KEY] as EntitiesModel;
if (dbContext != null)
{
dbContext.Dispose();
}
}
private void ClearSession()
{
if (HttpContext.Current.Session == null)
{
HttpContext.Current.Session.Remove(CONTEXT_KEY);
}
}
}
}
谁能帮我解决这个问题? 提前致谢!
【问题讨论】:
-
哇...这是我见过的最糟糕的概念,过于复杂,不能解决真正的问题,而且启动起来很危险。不要不将实体框架上下文放入会话中。很糟糕很糟糕。
-
@MystereMan:听起来他使用的是 Telerik OpenAccess,而不是 EF。
-
@SLaks - 错过了,但仍然......我无法想象这在 OpenAccess 下也是一个好主意。
-
@Mystere Man - 我应该怎么做才能纠正概念?这不是我的代码,我只是浏览 Telerik 视频并学习那些东西
标签: asp.net-mvc asp.net-mvc-3 telerik telerik-mvc telerik-open-access