Entity Framework error: There is already an open DataReader associated with this Command which must be closed first
On a recent project I started to use Entity Framework. So far the experience has been good, but sometimes I get some unexpected issues(and I have to force myself to not go back to NHibernate ).
Let’s have a look at the code first:
public class DemoContext:DbContext | |
{ | |
public DbSet<Category> Categories | |
{ | |
get; | |
set; | |
} | |
} | |
var context=new DemoContext(); | |
var categories=context.Categories; | |
foreach (var category in categories) | |
{ | |
Debug.WriteLine(category.Products.Count.ToString()); | |
} |
I think there’s nothing special about this code. I first load all the categories and then walk through all the products(which will cause a n+1 issue, but that’s another discussion). When I first ran this code it failed with the following error message:
"An error occurred while executing the command definition. See the inner exception for details."
When I drilled down to the innermost exception, the following message was shown:
"There is already an open DataReader associated with this Command which must be closed first."
To solve this, you have to add an extra part to your connection string:
Data Source=srv01;Initial Catalog=Northwind;Persist Security Info=True;Integrated Security=True;MultipleActiveResultSets=true