简体   繁体   English

实体框架实体中延迟加载时出错

[英]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: 这是我的ViewModel类:

    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: 这是我访问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(). 考虑在GetAllEnabledLatestStatusLog()中加载Service类的“Eager”。 Be sure to include using System.Data.Entity 请务必使用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 请参阅MSDN加载相关实体

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. 我说这里的问题是在你的查询中你没有显式加载相关的实体(在这种情况下, ServiceStatusHistory.Service ),大概是Lazy Loading默认开启。

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. 所以稍后当你引用item.Service.Name ,底层的EF类意识到它需要加载这些相关的实体 - 除了关联的ObjectContext (在这种情况下, EFDbContext )早已被处理掉。

So probably the simplest way to fix this is to modify your query to .Include() the related Service entities 因此,解决此问题的最简单方法可能是将查询修改为.Include()相关的Service实体

 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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