在EF5中加载子对象

本文关键字:对象 加载 EF5 | 更新日期: 2023-09-27 18:03:54

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

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
如何说EF加载Notifications对象?我知道Include,但我不能在GetUser方法中使用它。

在EF5中加载子对象

当第一个HttpRequest结束后查找您的CurrentUser对象,您的_repository引用,CurrentUser期待额外的查找,如EmailNotifications是不可用的。

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

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

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,它可以加载(如上所述),但也处理通知的执行(发送电子邮件等)。

您现在应该在应用程序会话缓存中有该用户的通知。

HTH