[英]load child objects in 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.
我知道當我從DB獲取User
時未Notifications
。
怎么說EF加載Notifications
對象? 我知道Include
,但我不能在GetUser
方法中使用它。
當第一個HttpRequest的仰視你結束后CurrentUser
對象,你_repository
參考該CurrentUser
期待更多的像查找EmailNotifications不可用。
該異常被拋出,因為CurrentUser
沒有原來的對象范圍內,所以你要么中的currentUser對象附加到你的新的ObjectContext _repository
使用,或使用簡單的通過新的環境,這是重裝用戶更容易的解決方案為存儲庫中的當前請求創建。
在嘗試在操作中查找通知之前,請添加以下行:
AppSession.CurrentUser = UserService.GetUser(AppSession.CurrentUser.Email);
AppSession.CurrentUser.Notifications.OfType<EmailNotification>().FirstOrDefault();
正如@Ryan 所說,這是由於對象上下文在相關通知中不可用於延遲加載。
我建議的是關閉延遲加載(如果可能的話),以后可能會導致很多問題,然后執行類似的操作......
var user = UserService.GetUser(AppSession.CurrentUser.Email);
user.Notifications = NotificationService.GetUserNotifications(user.Id /* or another identifier */);
AppSession.CurrentUser = user;
要做到這一點,你需要一個新的NotificationService,這可以加載(如上所述),但也處理通知的執行(發送電子郵件等)。
您現在應該在Application會話緩存中獲得該用戶的通知。
HTH
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.