简体   繁体   中英

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

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?

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.

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