Entity Framework,已经有一个打开的 DataReader 与此连接关联,必须先将其关闭
Entity Framework,There is already an open DataReader associated with this Connection which must be closed first
在"each"中,当运行时"FirstOrDefault"会报错"There is already an open DataReader associated with this Connection which must be closed first."。
怎么办?
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 =>
您正在使用 reader 迭代数据库中的项目
然后
var pu = users.FirstOrDefault(u => u.LoginName == m.Key);
第二个reader在第一个还在执行的时候进入,出现错误
调用ToList()将数据存入内存并关闭reader
var place = db.Place.Include(m => m.User).Where(m => dIds.Contains(m.Id)).ToList();
您还可以启用 MARS(多个活动结果集)
https://msdn.microsoft.com/en-us/library/h32h3abf(v=vs.110).aspx
在"each"中,当运行时"FirstOrDefault"会报错"There is already an open DataReader associated with this Connection which must be closed first."。 怎么办?
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 =>
您正在使用 reader 迭代数据库中的项目
然后
var pu = users.FirstOrDefault(u => u.LoginName == m.Key);
第二个reader在第一个还在执行的时候进入,出现错误
调用ToList()将数据存入内存并关闭reader
var place = db.Place.Include(m => m.User).Where(m => dIds.Contains(m.Id)).ToList();
您还可以启用 MARS(多个活动结果集)
https://msdn.microsoft.com/en-us/library/h32h3abf(v=vs.110).aspx