在"每个",当运行" FirstOrDefault"将出现错误"已经存在与此Connection关联的打开的DataReader,必须先关闭它。"。 怎么办?
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();
}
}
答案 0 :(得分:3)
当你说
时place.Each(m =>
您正在使用阅读器来迭代数据库中的项目
然后
var pu = users.FirstOrDefault(u => u.LoginName == m.Key);
第二个读取器在第一个读取器仍在执行时进入,并且发生错误
调用ToList()将数据存入内存并关闭阅读器
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