我的实体框架使用存在问题,并认为可能是因为我错误地使用了我的数据库上下文。
我偶尔会在日志中看到错误消息:“在创建模型时无法使用上下文。”
错误并不总是发生,似乎是在新的应用程序加载上,或者我编译项目并在编译时刷新浏览器选项卡。
下面的函数是错误的函数,从我的母版页调用。
public static class UserFunctions
{
private static peopleSwimmingContext _db = new peopleSwimming.Models.peopleSwimmingContext();
public static String GetUserRole(Int32 UserID) {
String returnedRole = String.Empty;
var foundUser = _db.Users.Where(w => w.UserId == UserID).FirstOrDefault();
if (foundUser != null)
{
returnedRole = foundUser.Role.Name;
}
return returnedRole;
}
}
任何提示都会受到大力赞赏!
哦,这是我的内心追踪:
内部堆栈追踪:
System.Data上的System.Data.Entity.InternalContext.Initialize()处的System.Data.Entity.Internal.LazyInternalContext.InitializeContext()处于System.Data.Entity.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)。 Data.Entity.Internal.Linq.InternalSet 1.Initialize() at System.Data.Entity.Internal.Linq.InternalSet
1.get_InternalContext()at System.Data.Entity.Infrastructure.DbQuery 1.System.Linq.IQueryable.get_Provider() at System.Linq.Queryable.Where[TSource](IQueryable
1 source,Expression`1谓词)at PeopleSwimming.Logic.UserFunctions.GetUserRole (int32 UserID)位于c:\ svn \ peopleSwim \ peopleSwimming \ Logic \ UserFunctions.cs:第18行,位于c:\ svn \ peopleSwim \ peopleSwimming \ Home.aspx.cs中的peopleSwimming._Home.Page_Load(Object sender,EventArgs e) :System.Web上的System.Web.UI.Control.LoadRecursive()上System.Web.UI.Control.OnLoad(EventArgs e)的System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender,EventArgs e)第25行.UI.Page.ProcessRequestMain(布尔includeStagesBeforeAsyncPoint,布尔includeStagesAfterAsyncPoint)
答案 0 :(得分:3)
尝试将代码包装在using
语句中,该语句初始化并处理数据上下文,因此只有在您需要它之后才可以使用它。这也将确保它被处置掉。
此外,您不需要Where
方法,只需使用FirstOrDefault
。
public static class UserFunctions
{
public static String GetUserRole(Int32 UserID)
{
using (peopleSwimmingContext _db = new peopleSwimming.Models.peopleSwimmingContext())
{
String returnedRole = String.Empty;
var foundUser = _db.Users.FirstOrDefault(w => w.UserId == UserID);
if (foundUser != null)
{
returnedRole = foundUser.Role.Name;
}
return returnedRole;
}
}
}