2013-04-22 30 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

相關問題