在EF5中加载子对象

时间:2013-03-14 07:20:29

标签: c# entity-framework entity-framework-5

我的通用存储库中有一个方法:

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获取NotificationsUser未加载  怎么说EF加载Notifications个对象?我知道Include,但我无法在GetUser方法中使用它。

2 个答案:

答案 0 :(得分:2)

当第一个HttpRequest在查找您的CurrentUser对象后结束时,_repository CurrentUser引用期望其他查找(例如EmailNotifications)的引用不可用。

抛出异常是因为CurrentUser没有原始对象上下文,因此您必须将CurrentUser对象附加到_repository正在使用的新objectContext,或者使用通过为存储库中的当前请求创建的新上下文简单地重新加载用户的简单解决方案。

在尝试在操作中查找通知之前,请添加以下行:

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

答案 1 :(得分:1)

作为@Ryan said,这是因为对象上下文不适用于关联通知中的延迟加载。

我建议关闭延迟加载(如果可能),以后可能会导致很多问题,然后执行类似的操作...

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

为此,您需要一个新的NotificationService,这可以加载(如上所述),但也可以处理通知的执行(发送电子邮件等)。

您现在应该在应用会话缓存中收到该用户的通知。

HTH

相关问题