I have a sample application with the following models and context-
public class Department
{
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 virtual Department Department { get; set; }
}
public class TestContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Department> Departments { get; set; }
}
Below is the progarm.cs code. When i debug and the debugger reach - Consol.WriteLine method inside foreach block, i get the error- There is already an open DataReader associated with this Command which must be closed first. Why is that. Should not context close automatically once it opens connection when the foreach code is reached.
class Program
{
static void Main(string[] args)
{
using (var context = new TestContext())
{
var students = context.Students.Where(s => s.Id == 1);
foreach (var student in students)
{
Console.WriteLine("Student : {0} - Department {1}", student.Name, student.Department.Name);
}
Console.ReadLine();
}
}