C# DbContext用法和属性值
首先,让我们先说我是新手。也就是说,我正在使用MVC3 w/EF4.3.1和db优先的方法在C#中构建一个web应用程序。在登录过程中,我想设置一些在整个应用程序中使用的会话变量 我的问题是,我不确定如何将值读入会话变量。以下是AccountController.cs中当前的代码:C# DbContext用法和属性值,c#,asp.net-mvc-3,properties,dbcontext,entity-framework-4.3,C#,Asp.net Mvc 3,Properties,Dbcontext,Entity Framework 4.3,首先,让我们先说我是新手。也就是说,我正在使用MVC3 w/EF4.3.1和db优先的方法在C#中构建一个web应用程序。在登录过程中,我想设置一些在整个应用程序中使用的会话变量 我的问题是,我不确定如何将值读入会话变量。以下是AccountController.cs中当前的代码: [HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl) { if (ModelState.IsValid) {
[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短语的实体(CPluntities)相关的内容
我发现的一些链接:
Scott,当我尝试使用代码块中的第一行时,
使用(var context=new DbContext())
我得到一个关于“System.Data.Entity.DbContext.DbContext()”的错误,因为它的保护级别,我知道我被卡住了。。。我不知道应该用什么来代替DbContext()。但是,如果我确实需要进行您建议的修改,我不会感到惊讶。您应该看到在类名之前修改了访问权限,类似于“public partial class DbContext”。如果它说的不是“公共”(如受保护的、私有的或内部的),请尝试将其更改为“公共”,看看这是否解决了问题。但如果看不到您的代码,可能会很困难。通常,实体框架会创建DbContext的派生版本。使用基类很可能不起作用。我认为OP使用DbContext作为对其上下文名称的泛型引用。我想我应该更具体一点。:)嗯,这似乎让我接近了我所需要的。代码不再返回错误。现在我需要弄清楚为什么会话变量是空的…你是怎么开始的?在某个时候,您必须创建一个EF模型,可能包含一个从ObjectContext或DbContext派生的类。尝试查找该类并在using
语句中使用它。
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;
}