2013-03-14 67 views
1

對象我有一個方法,在我的通用倉庫:負載孩子EF5

public IQueryable<T> Query<T>() where T : class, IEntity 
{ 
    return _context.Set<T>(); 
} 

這是獲取用戶的方法:

public User GetUser(string email) 
{ 
    return _repository.Query<User>().FirstOrDefault(u => u.Email == email); 
} 

最後,我把用戶會話:

AppSession.CurrentUser = UserService.GetUser(email); 

在我的行動中,我需要獲得當前用戶並獲得對象集合Notifications(一對多):

AppSession.CurrentUser.Notifications.OfType<EmailNotification>().FirstOrDefault(); 

但是,在這裏我得到的錯誤:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. 

我知道Notifications當我從DB獲得User沒有加載。
How to say EF加載Notifications對象?我知道Include,但我不能在GetUser方法中使用它。

回答

2

當查找到CurrentUser對象後第一個HttpRequest結束時,您的_repository引用表明CurrentUser期望進行其他查找,如EmailNotifications不可用。

拋出異常,因爲CurrentUser沒有原來的對象範圍內,所以你要麼中的currentUser對象附加到你的_repository使用新的ObjectContext,或使用簡單的通過重裝用戶更容易的解決方案爲存儲庫中的當前請求創建的新上下文。

之前試圖找到在你的行動通知,添加以下行:

AppSession.CurrentUser = UserService.GetUser(AppSession.CurrentUser.Email); 
AppSession.CurrentUser.Notifications.OfType<EmailNotification>().FirstOrDefault(); 
1

由於@Ryan said這是由於該對象的上下文是不可偷懶負載相關的通知。

我會建議被關閉延遲加載(如果可能的話)稍後會引起很多問題,然後像做...

var user = UserService.GetUser(AppSession.CurrentUser.Email); 
user.Notifications = NotificationService.GetUserNotifications(user.Id /* or another identifier */); 
AppSession.CurrentUser = user; 

要做到這一點,你需要一個新的NotificationService,這可以加載(如上所述),但也可以處理通知的執行(發送電子郵件等)。

您現在應該在應用程序會話高速緩存中爲該用戶提供通知。

HTH