MVC CodeFirst计算属性获取错误”;ObjectContext实例已释放”;
本文关键字:ObjectContext 释放 实例 取错误 CodeFirst 计算 属性 获取 MVC | 更新日期: 2023-09-27 17:57:30
我有一个ASP。NET MVC Code First网站。我有一个模型Teacher
,它有一个Student
的列表,每个列表都有一个计算的属性CompletedTests
。当我试图从包含Student
s列表的ViewModel中访问计算属性CompletedTests
时,出现以下错误:
An exception of type 'System.ObjectDisposedException' occurred in EntityFramework.dll but was not handled in user code
Additional information: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
教师:
public class Teacher
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Student> Students{ get; set; }
}
学生:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int TeacherId { get; set; }
public virtual Teacher Teacher { get; set; }
public int TotalTests
{
get
{
return Tests.Count;
}
}
public int CompletedTests
{
get
{
return Tests.Count(p => p.IsCompleted);
}
}
public virtual ICollection<Test> Tests{ get; set; }
}
测试:
public class Test
{
public int Id { get; set; }
public int StudentId { get; set; }
public int QuestionsTotal
{
get
{
return Questions.Count;
}
}
public bool IsCompleted
{
get
{
return Questions.Count(q => q.Completed) >= QuestionsTotal;
}
}
public virtual Student Student { get; set; }
public virtual ICollection<Question> Questions{ get; set; }
}
问题:
public class Question
{
public int Id { get; set; }
public int TestId { get; set; }
public virtual Question Question { get; set; }
}
HomeViewModel:
public class HomeViewModel
{
public string TeacherName { get; set; }
public int StudentCount { get; set; }
public IEnumerable<Student> Students { get; set; }
}
家庭控制器:
public ActionResult Index()
{
var model = new HomeViewModel();
var userId = User.Identity.GetUserId();
using (var context = new ApplicationDbContext())
{
var teacher = context.Teachers.FirstOrDefault(c => c.IdentityId == userId);
if (teacher != null)
{
model.TeacherName = teacher.Name;
model.Students = teacher.Students.ToList();
}
return View(model);
}
}
Index.chtml部分:
<tbody>
@foreach (var student in Model.Students)
{
<tr>
<td>
@student.Name
</td>
<td>
@(student.CompletedTests + "/" + student.TotalTests)
</td>
</tr>
}
</tbody>
有人能指出为什么我在student.CompletedTests
部分得到已处理的实例错误吗?
加载学生实体时使用Include包含测试实体以避免延迟加载:
model.Students = teacher.Students.Include(t => t.Tests).ToList();
这被称为热切加载:
https://msdn.microsoft.com/en-us/data/jj574232.aspx
您得到的错误是因为ObjectContext(ApplicationDbContext)在您的视图中不再可用。它已经在控制器的方法中进行了处理。