开发者

I am using linq and I am getting the error "There is already an open datareader associated with this command which must be closed first"

dc.Accounts.Where(a => blogs.Select(b => b.AccountID).Distinct()
           .Contains(a.AccountID));
foreach (Blog blog in blogs)
{
    blog.Account = accounts.Where(a => a.AccountID == blog.AccountID)
                           .FirstOrDefault();

    //this is done to access account outside ObjectContext
    blog.account = blog.Account;
}

In this code I am getting the value until the foreach loop blog, but then I am getting the error

There is already an open datareader associated with this 开发者_如何学编程command which must be closed first.


This is usually caused when you have an outer and inner query, and the outer is still running. Usually you can fix this by forcing the outer query to complete; simply adding ToList() is usually enough:

var blogs = dc.Accounts.Where(a => blogs.Select(b => b.AccountID).Distinct()
       .Contains(a.AccountID)).ToList(); // <======= here


You need to enable Multiple Active Result Sets.

Modify your connection string to enable MultipleActiveResultSets

string connectionString = "Data Source=MSSQL1;" + 
    "Initial Catalog=AdventureWorks;Integrated Security=SSPI" +
    "MultipleActiveResultSets=True";

Since you are accessing some navigational properties inside the loop you may be running into Select N+1 problem. You can avoid this by eager loading.

eg:

dc.Accounts.Include("Blogs").Where(a => blogs.Select(b => b.AccountID).Distinct()
           .Contains(a.AccountID));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜