System.ObjectDisposedException when trying to receive the data from a List

笑着哭i 提交于 2020-01-05 09:23:30

问题


Hello I am writing an ASP.Net MVC application and I have a special class dedicated for Database connection. In my HomeController I call the static methods of this special DB class, which return the needed data into objects. I use the Entity Framework in order to achieve this. However I get a strange exception when I try to use the List from my Controller. I believe that the problem is that I have a virtual inner collection that is disposed after the entity framework methods are done. I can access the main-group fields, but can't access the inner Lists. Here is my model:

public partial class Teacher
{
    public Teacher()
    {
        this.TeacherRelationships = new List<TeacherRelationship>();
        this.CourseTemplates = new List<CourseTemplate>();
        this.Orders = new List<Order>();
    }

    public int ID { get; set; }
    public string Name { get; set; }
    public string DescriptionText { get; set; }
    public Nullable<int> Phone { get; set; }
    public string Email { get; set; }
    public string PictureFilePath { get; set; }
    public virtual ICollection<TeacherRelationship> TeacherRelationships { get; set; }
    public virtual ICollection<CourseTemplate> CourseTemplates { get; set; }
    public virtual ICollection<Order> Orders { get; set; }
}

When I try to get the CourseTemplate results I get this exception:

Exception Details: System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

I tried to investigate it alone, but everything I found is the suggestion to return a List instead of a query. Here is also the code for my DBConnection method:

    public static List<Teacher> returnAllTeachers()
    {
        using (var db = new Context())
        {
            var query = from th in db.Teachers
                        select th;

            return query.ToList();
        }
    }

What am I doing wrong?


回答1:


Your original query only loads the Teacher objects. The collections are set to be lazy loading to not be fetched until you access them. Unfortunately at that point, your objectcontext is closed so you can no longer fetch anything from your database.

The best fix is to update the query to eager load the additional data you want to use:

var query = from th in db.Teachers.Include(t => t.Orders)
            select th;

You also have to add a using System.Data.Entity to get access to the Include() method that takes a lambda. Don't use the one taking strings.



来源:https://stackoverflow.com/questions/19928062/system-objectdisposedexception-when-trying-to-receive-the-data-from-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!