Skip to main content
 首页 » 编程设计

c#之尝试从列表接收数据时出现 System.ObjectDisposedException

2024年02月13日15jpfss

你好,我正在编写一个 ASP.Net MVC 应用程序,我有一个专门用于数据库连接的特殊类。在我的 HomeController 中,我调用这个特殊 DB 类的静态方法,它将所需的数据返回到对象中。我使用 Entity Framework 来实现这一点。但是,当我尝试使用我的 Controller 中的列表时,出现了一个奇怪的异常。我认为问题在于我有一个虚拟内部集合,它是在 Entity Framework 方法完成后处理的。我可以访问主组字段,但无法访问内部列表。这是我的模型:

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; } 
} 

当我尝试获取 CourseTemplate 结果时出现此异常:

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

我试图单独调查它,但我发现的所有内容都是建议返回列表而不是查询。这也是我的 DBConnection 方法的代码:

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

我做错了什么?

请您参考如下方法:

您的原始查询仅加载 Teacher 对象。这些集合被设置为延迟加载,在您访问它们之前不会被获取。不幸的是,此时您的 objectcontext 已关闭,因此您无法再从数据库中获取任何内容。

最好的解决方法是将查询更新为eager load您要使用的额外数据:

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

您还必须添加 using System.Data.Entity 以访问采用 lambda 的 Include() 方法。不要使用带字符串的那个。