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.


