我使用ASP.NET MVC 4和SQL Server 2008开发了一个Web应用程序,我创建了ContextManager类,在所有页面中只有一个数据库上下文.
public static class ContextManager
{
public static HotelContext Current
{
get
{
var key = "Hotel_" + HttpContext.Current.GetHashCode().ToString("x")
+ Thread.CurrentContext.ContextID.ToString();
var context = HttpContext.Current.Items[key] as HotelContext;
if (context == null)
{
context = new HotelContext();
HttpContext.Current.Items[key] = context;
}
return context;
}
}
}
Run Code Online (Sandbox Code Playgroud)
它在大多数页面中都能正常工作,但是在注册页面出现问题并且我的上下文因以下错误而被废弃:
由于已经处理了DbContext,因此无法完成操作.
public ActionResult Register ( RegisterModel model )
{
if ( ModelState.IsValid )
{
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount( model.UserName, model.Password,
new
{
Email = model.Email, …Run Code Online (Sandbox Code Playgroud)