2013-04-22 33 views
0

我遇到了我的实体框架用法问题,并认为这可能是因为我错误地使用了我的数据库上下文。创建模型时无法使用上下文

每隔一段时间我都会在日志中看到错误消息,指出:“模型创建时无法使用上下文。”

错误并不总是会发生,似乎是在新的应用程序加载或编译我的项目并刷新浏览器选项卡,而它正在编译。

下面的函数是错误的,并从我的母版页被调用。

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; 
    } 
} 

任何提示将大规模赞赏!

哦,这里是我的innerstack跟踪:

内堆栈跟踪:

在System.Data.Entity.Internal.LazyInternalContext.InitializeContext()在System.Data.Entity.Internal.InternalContext.Initialize ()at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)at System.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,表达式1谓词)在peopleSwimming.Logic.UserFunctions.GetUserRole(Int32用户ID)在c:\ svn \ peopleSwim \ peopleSwimming \ Logic \ UserFunctions.cs中:第18行在peopleS在System.Web.Util.CalliEventHandlerDelegateProxy.Callback(对象发件人,EventArgs e)中的第25行c:\ svn \ peopleSwim \ peopleSwimming \ Home.aspx.cs中的wimming._Home.Page_Load(Object sender,EventArgs e) Web.UI.Control.OnLoad(EventArgs e)在System.Web.UI.Control.LoadRecursive()在System.Web.UI.Page.ProcessRequestMain(布尔includeStagesBeforeAsyncPoint,布尔includeStagesAfterAsyncPoint)

回答

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; 
     } 
    } 
} 
+0

感谢有关where语句在first或default和using块中的信息。我已经改变了这个函数来使用使用块,所以希望我会更少看到错误! – L2wis 2013-04-22 10:05:12

+0

你看到它不太经常? – 2013-09-11 18:14:20

相关问题