简体   繁体   中英

Error with lazy loading in Entity Framework Entity

I am having an error on my web page:

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

It occours herein my view:

@model Service_Monitor_Web_Interface.Models.DashBoardViewModel
...    
=> @Html.DisplayFor(modelItem => item.Service.Name)

Here is my ViewModel class:

    public class DashBoardViewModel
{

    public int NumberOfUsers { get; set; }

    public virtual IEnumerable<ApplicationUser> recentUsers { get; set; }

    public virtual IEnumerable<UserActivityLog> logs { get; set; }

    public virtual IList<Service_Monitor_Domain.Entities.ServiceStatusHistory> serviceStatus { get; set; }

}

Here is my controller for the class:

   public ActionResult Index()
    {
        DashBoardViewModel vm = new DashBoardViewModel();  

        var dbs = new EFServiceStatusHistoryRepository();

        vm.serviceStatus = dbs.GetAllEnabledLatestStatusLog();

        return View(vm);
    }

and here is my function that access the db:

  public List<ServiceStatusHistory> GetAllEnabledLatestStatusLog()
    {
        List<ServiceStatusHistory> list = null;
        try
        {
            using (var db = new EFDbContext())
            {
                //var results = db.ServiceStatusHistory.Where(h => h.Service.Enabled)
                //                  .OrderByDescending(h => h.Id)
                //                  .GroupBy(h => h.Service.Id)
                //                  .Select(grp => grp.FirstOrDefault());

                var results = db.ServiceStatusHistory
                            .Where(x => x.Service.Enabled)
                            .GroupBy(x => x.Service)
                             .Select(x => x.OrderByDescending(y => y.time).FirstOrDefault());

                list = results.ToList();
            }
            return list;
        }
        catch
        {
            //Error
        }
        return list;
    }

Here is my entity:

    public class ServiceStatusHistory
{
    [Key]
    [Required]
    public int Id { get; set; }

    // Forenkey to service
    [Required]
    public virtual Service Service { get; set; }

    [Required]
    public ServiceStatus Status { get; set; }

    [Required]
    public string Messages { get; set; }

    [Required]
    //Time Logged in the db
    public DateTime time { get; set; }

    [Required]
    //Time the service last called the update method on the client
    public DateTime LastUpdateTime { get; set; }
 }

I think it has something to do with lazy loading. But I have not had this problem before when querying the same table? However it was just a simple select query.

Consider "Eager" loading of the Service class in your GetAllEnabledLatestStatusLog(). Be sure to include using System.Data.Entity
using System.Data.Entity var results = db.ServiceStatusHistory .Include("Service") .Where(x => x.Service.Enabled) .GroupBy(x => x.Service) .Select(x => x.OrderByDescending(y => y.time).FirstOrDefault()); See MSDN Loading Related Entities

I'd say that the problem here is that in your query you are not explicitly loading the related entities (in this case, ServiceStatusHistory.Service ), presumably Lazy Loading is on by default.

So later on when you refer to item.Service.Name , the underlying EF class realises that it needs to load these related entities - except that the associated ObjectContext (in this case, EFDbContext ) has long since been disposed.

So probably the simplest way to fix this is to modify your query to .Include() the related Service entities

 var results = db.ServiceStatusHistory
                    .Include("Service")
                    .Where(x => x.Service.Enabled)
                    .GroupBy(x => x.Service)

                    .Select(x => x.OrderByDescending(y => y.time).FirstOrDefault());

or you could turn off lazy loading for that query:

using (var db = new EFDbContext())
{
   db.Configuration.LazyLoadingEnabled=false;
   //use original query here
}

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