У меня есть первый сайт ASP.NET MVC Code. У меня есть модель Teacher
, которая имеет список Student
s, каждый из которых имеет рассчитанное свойство CompletedTests
. Я получаю следующее сообщение об ошибке при попытке получить доступ к вычисляемому свойству CompletedTests
изнутри ViewModel, который содержит список Student
с:MVC CodeFirst Calculated Property get error «Объект ObjectContext удален»
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.cshtml раздел:
<tbody>
@foreach (var student in Model.Students)
{
<tr>
<td>
@student.Name
</td>
<td>
@(student.CompletedTests + "/" + student.TotalTests)
</td>
</tr>
}
</tbody>
Может ли кто-нибудь указать, почему я получаю удаленную ошибку экземпляра на части student.CompletedTests
?
Я не вижу, где вы получаете «Имя» для учителя или ученика. У вас есть только поле «Имя» в «Тест». –
Извините, если бы он был не в том классе. Это на «Студент», а не на «Тест». – Marcus
Что относительно 'teacher.Name'? –