Entity Framework,There is already an open DataReader associated with this Connection which must be closed first

牧云@^-^@ 提交于 2019-12-24 17:19:32

问题


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();
    }
}

回答1:


When you say

place.Each(m =>

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

Then

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

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

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();

You can also enable MARS (Multiple Active Result Sets)

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



来源:https://stackoverflow.com/questions/43264526/entity-framework-there-is-already-an-open-datareader-associated-with-this-connec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!