Entity Framework ObjectContext and Reporting

I had an email this morning from someone who was having trouble with reports populated using Entity Framework.

He was running a report repeatedly but changing the filter.

For example, Customers whose last name is Smith, then Customers whose last name is Barber.

The problem was that after running the Smith report, the Smiths were showing up on the Barber report.

The problem is that he was using one context to generate both reports.

The context just keeps collecting all of the entities you feed into it. More accurately, the context keeps collecting ObjectStateEntries (which manage the state for an instantiated entity and act as pointers back to the entity objects in memory) for all of the entities you feed to it.

Best to just have a context that exists only for the life time of the method which gets the report data.

Public List<Customer> GetCustomers(string lastname)
{
   using (var context=new MyEntities()) 
  {
     return context.Customers.Where(c=>c.LastName==lastname).ToList();
  }
} 

Now you don’t have to worry about cached entities. 

This is not a hard rule but a guideline. For example, one exception would be when you are drilling in to reports.

  Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!  

2 thoughts on “Entity Framework ObjectContext and Reporting

  1. The sample code won’t work, because the context will need to be disposed before the method returns. The return needs a ".ToList()" on the end.

    Thanks for your EF 4 posts!

  2. That’s what I get for coding in Windows Live Writer.

    Actually that won’t happen. It won’t even compile becasue my signature says I’m returning a List and I forgot to. I’m just retunring a query. My signature is correct and I have warned people over and over not to return queries from methods because of an out of scope context.. Thanks for pointing out my, umm, typo.

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

This site uses Akismet to reduce spam. Learn how your comment data is processed.