实体框架,已经有与此连接关联的打开的DataReader,必须先关闭 [英] Entity Framework,There is already an open DataReader associated with this Connection which must be closed first

查看:105
本文介绍了实体框架,已经有与此连接关联的打开的DataReader,必须先关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在每个中,运行 FirstOrDefault时将错误提示已存在与此Connection关联的打开的DataReader,必须先关闭它。
怎么办?

In the "each", when run the "FirstOrDefault" will error "There is already an open DataReader associated with this Connection which must be closed first.". How to do ?

public int SetUser(string[] dIds, string pId)
{
    using (var scope = _dbContextScopeFactory.Create())
    {
        var db = scope.DbContexts.Get<JuCheapContext>();

        var users = db.Users;

        var user = users.FirstOrDefault(m => m.Id == pId);
        if (user.Places == null)
        {
            user.Places = new List<PlaceEntity>();
        }

        var place = db.Place.Include(m => m.User).Where(m => dIds.Contains(m.Id));

        place.Each(m =>
        {
            user.Places.Add(m);

            //There is already an open DataReader associated with this Connection which must be closed first.
            var pu = users.FirstOrDefault(u => u.LoginName == m.Key);

            if (pu != null)
            {
                pu.FId = pId;
            }

        });

        return db.SaveChanges();
    }
}


推荐答案

何时你说

place.Each(m =>

您正在使用读取器来迭代数据库中的项目

You're using a reader to iterate the items from the database

然后

  var pu = users.FirstOrDefault(u => u.LoginName == m.Key);

第二个读取器进入,而第一个读取器仍在执行并且发生错误

The second reader enters while the first one is still executing and the error occurs

调用ToList()将数据存入内存并关闭读取器

Call ToList() to get the data into memory and close the reader

var place = db.Place.Include(m => m.User).Where(m => dIds.Contains(m.Id)).ToList();

您还可以启用MARS(多个活动结果集)

You can also enable MARS (Multiple Active Result Sets)

https://msdn.microsoft.com/zh-CN/library/h32h3abf(v = vs.110).aspx

这篇关于实体框架,已经有与此连接关联的打开的DataReader,必须先关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆