Alternatively to using MARS (MultipleActiveResultSets) you can write your code so you dont open multiple result sets.
What you can do is to retrieve the data to memory, that way you will not have the reader open. It is often caused by iterating through a resultset while trying to open another result set.
Sample Code:
public class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; } } public class Blog { public int BlogID { get; set; } public virtual ICollection<Post> Posts { get; set; } } public class Post { public int PostID { get; set; } public virtual Blog Blog { get; set; } public string Text { get; set; } }
Lets say you are doing a lookup in your database containing these:
var context = new MyContext(); //here we have one resultset var largeBlogs = context.Blogs.Where(b => b.Posts.Count > 5); foreach (var blog in largeBlogs) //we use the result set here { //here we try to get another result set while we are still reading the above set. var postsWithImportantText = blog.Posts.Where(p=>p.Text.Contains("Important Text")); }
We can do a simple solution to this by adding .ToList() like this:
var largeBlogs = context.Blogs.Where(b => b.Posts.Count > 5).ToList();
This forces entityframework to load the list into memory, thus when we iterate though it in the foreach loop it is no longer using the data reader to open the list, it is instead in memory.
I realize that this might not be desired if you want to lazyload some properties for example. This is mostly an example that hopefully explains how/why you might get this problem, so you can make decisions accordingly