2012-12-19 17 views
0

首先,让我们开始说我是菜鸟。这就是说,我正在使用数据库优先方法在C#中使用MVC3 w/EF4.3.1构建Web应用程序。在登录过程中,我想设置一些会在整个应用程序中使用的会话变量。DbContext的用法和属性值

我的问题是,我不知道如何去读取会话变量的值。下面是代码目前在AccountController.cs:

[HttpPost] 
public ActionResult LogOn(LogOnModel model, string returnUrl) 
{ 
    if (ModelState.IsValid) 
    { 
     if (Membership.ValidateUser(model.UserName, model.Password)) 
     { 
      FormsAuthentication.SetAuthCookie(model.UserName, 
               model.RememberMe); 
      if (Url.IsLocalUrl(returnUrl) 
       && returnUrl.Length > 1 
       && returnUrl.StartsWith("/") 
       && !returnUrl.StartsWith("//") 
       && !returnUrl.StartsWith("/\\")) 
      { 
       return Redirect(returnUrl); 
      } 
      else 
      { 
       return RedirectToAction("Index", "Home"); 
      } 
     } 
     else 
     { 
      ModelState.AddModelError("", 
       "The user name or password provided is incorrect."); 
     } 
    } 

    // If we got this far, something failed, redisplay form 
    return View(model); 
} 

,从我看过,我应该尝试使用的DbContext访问给定域的属性,类似于:

using (var context = new DbContext()) 
{ 
    var svc100 = context.SVC00100.Where(t => 
         t.TECHEMAIL.Contains("model.UserName") 

    // Read the current value of the Name property 
    Session["Name"] = context.Entry(svc100).Property(u => 
               u.Name).CurrentValue; 
} 

现在......我如何确定在第二个代码块中应该用什么来代替DbContext()?如果我尝试使用下拉菜单并选择需要的内容,则看不到与包含DbContext短语的实体(CPLUEntities)相关的任何内容。

一些我发现的链接:

Implement custom “ValidateUser” in MembershipProvider

Entity Framework Working with Property Values

Using DbContext in EF 4.1 Part 5: Working with Property Values

+0

你是如何开始的?在某些时候,您必须创建一个EF模型,可能包含从ObjectContext或DbContext派生的类。试着找到那个类并在你的'using'语句中使用它。 –

回答

2
using (var context = new DbContext()) 
    { 
    var svc100 = context.SVC00100 
       .FirstOrDefault(t => t.TECHEMAIL.Contains(model.UserName)); 

    // Read the current value of the Name property 
    if (svc100 != null && !String.IsNullOrEmpty(svc100.Name)) 
     Session["Name"] = svc100.Name; 
    } 
+0

Scott,当我尝试使用该代码块中的第一行'using(var context = new DbContext())'我得到一个关于_'System.Data.Entity.DbContext.DbContext()'的错误,由于其无法访问保护level_这就是我知道我被卡住的地方......我无法弄清楚应该代替** DbContext()**。不过,如果我确实需要进行修改,我不会感到惊讶。 –

+0

打开DbContext()的类文件。你应该在类名之前看到修改的访问,比如“public partial class DbContext”。如果它说的不是'公共'(如受保护的,私人的或内部的),请尝试将其改为'公开',看看是否能解决问题。如果没有看到你的代码,可能会很困难。 – Scott

+0

通常,实体框架会创建DbContext的派生版本。使用基类很可能不起作用。 –