简体   繁体   中英

load child objects in EF5

I have a method in my generic repository:

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

This is method for getting user:

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

Finally, I put the user to session:

AppSession.CurrentUser = UserService.GetUser(email);

In my action I need to get the current user and get collection of objects Notifications (one-to-many):

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

But, here I get the error:

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

I know that Notifications not loaded when I getting User from DB.
How to say EF to load Notifications objects? I know about Include , but I cannot use it in GetUser method.

When the first HttpRequest ends after looking up your CurrentUser object, your _repository reference that the CurrentUser is expecting for additional lookups like EmailNotifications isn't available.

The exception is thrown because CurrentUser doesn't have the original object context, so you either have to attach the CurrentUser object to the new objectContext that your _repository is using, or use the easier solution of simply reloading the user through the new context that was created for your current request in the repository.

Before attempting to find the notifications in your action, add the following line:

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

As @Ryan said it is due to the fact that the object context is not available to lazy load in the associated notifications.

What I'd suggest is turn off lazy loading (if possible) as can cause lots of issues later and then do something like ...

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

To do this you will require a new NotificationService, this can load (as suggested above) but also handle the execution of notifications (sending emails etc).

You should now have the notifications for that user in your Application session cache.

HTH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM