Npgsql + EF不会关闭读者

时间:2016-12-08 09:50:33

标签: c# postgresql entity-framework-core

我尝试使用Npgsql将ASP.Net MVC5项目移植到PostgreSQL。但是这段代码有错误:

public ActionResult Index()
{
    var roles = Roles.GetAll();

    foreach (var role in roles)
    {
        if (!RoleManager.RoleExists(role))
        {
            var identityRole = new IdentityRole() { Name = role };
            var result = RoleManager.Create(identityRole);
            // Check a creation result
            if (!result.Succeeded)
            {
                Logger.Error(string.Format("Role '{0}' can't be created.", role));
            }
        }
    }
    //Detect root administrators count
    var rootRole = RoleManager.FindByName(Roles.Root);
    ViewData["userCount"] = rootRole.Users.Count;
    List<KpiViewModel> kpies;
    //Build KPIs
    using (var db = new DatabaseContext())
    {
        var staffs = db.Staff.Where(s => s.TasksStaff.Count > 0);
        kpies = new List<KpiViewModel>(staffs.Count());

        foreach (var s in staffs)
        {
            var item = new KpiViewModel();
            item.Id = s.Id;
            item.Name = string.Format("{0} {1} {2}", s.LastName, s.FirstName, s.Patronymic);
            var tasks = s.TasksStaff.Select(ts => ts.Task).Where(t => t.ClosedOn.HasValue);

            float percent = 0f;
            int total = tasks.Count();

            if (total > 0)
            {
                var closed = (float)tasks.Where(t => t.EndDate.Date.CompareTo(t.ClosedOn.Value.Date) >= 0).Count();
                percent = closed / total * 100;
                item.Percent = percent;
            }

            var ks = db.Kpi.Where(k => k.Percent <= percent).OrderByDescending(k => k.Percent);
            var kpi = ks.FirstOrDefault();
            var tint = 0xEEEEEE; //Default color RGB 238, 238, 238

            if (kpi != null)
            {
                tint = kpi.Tint;
            }

            item.Tint = '#' + tint.ToString("X6");
            kpies.Add(item);
        }
    }

    return View(kpies);
}

错误: An operation is already in progress. var kpi = ks.FirstOrDefault();代码字符串。{ 如何解决?

1 个答案:

答案 0 :(得分:2)

你的行

var staffs = db.Staff.Where(s => s.TasksStaff.Count > 0);

已经在运行了。您可以添加ToList()以使其撤回数据,即

var staffs = db.Staff.Where(s => s.TasksStaff.Count > 0).ToList();