Skip to content

Using The DataContext In EntityFramework To Retrieve Nested Objects

Updated: at 02:12 PM

I’m always somewhat amazed when I read something from documentation that is not straight forward and it actually works.  So amazed and excited that I often feel the need to blog about it.

So, here is the problem.  I created a CodeFirst implementation of EntityFramework in Visual Studio and created a simple hierarchy in my data model.  That is, without showing all the code, here is what I have:

public class Person
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

public virtual List<EmailAddressInfo> EmailAddressInfoList { get; set; }
..
}

public class EmailAddressInfo
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

public string EmailAddress { get; set; }

}

public class EmailAccount
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
...
}

Now, if you execute a LINQ command like the following:

var recs = (from data in db.Persons
select data);
foreach (var rec in recs)
{
foreach (var email in rec.EmailAddressInfoList)
{
Console.WriteLine(email);
}
}

You get the error:

Exception Details: System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.

 

image

 

To solve this, you need to tell EntityFramework/CodeFirst to include the EmailAddressInfoList in the query.  All you need to do is change the db.Persons to db.Persons.Include("EmailAddressInfoList") as follows:

 

var recs = (from data in db.Persons.Include("EmailAddressInfoList")
select data);

 

Then, it all works!

Hope this helps.

Check out the ORM (Object Relational Mapper) PRISMA. The database access method I use in all my projects