操作无法完成,因为 DbContext 已被释放。”

operation cannot be completed because the DbContext has been disposed."

虽然 运行 项目出现此错误 "The operation cannot be completed because the DbContext has been disposed"。在检查网络时,我已经看到了很多答案,但我想我的 code.Please 中有所有这些,验证我的代码,让我知道它有什么问题,请帮助我...... 这是在控制器和 Elmah 中编写的代码出现错误。

 public ActionResult Create(Permissions permissions)
    {
        try
        {
            using (var db = new AdminDb())
            {
                //delete existing permissions of the selected role..
                IList<int> ModuleMenu = (from d in db.MenuConfig.AsNoTracking()
                                         where d.ModuleId == permissions.ModuleId
                                         select d.MenuConfigId).ToList();

                var RoleMenu = (from c in db.RoleMenuMapping where ModuleMenu.Contains((int)c.MenuId) && c.RoleId == permissions.RoleId select c).ToList();

                foreach (var rm in RoleMenu)
                {
                    db.RoleMenuMapping.Remove(rm);
                    db.SaveChanges(); // Added for avoiding The object is in a detached state Error
                }

                // add new permissions to db
                if (permissions.RoleMenu != null)
                {
                    foreach (var rm in permissions.RoleMenu)
                    {
                        RoleMenuMapping RoleMapping = new RoleMenuMapping();
                        //to get the next ID
                        string EntityName = (db as IObjectContextAdapter).ObjectContext.CreateObjectSet<RoleMenuMapping>().EntitySet.Name;
                        Int32 nextval = new Assyst.PanERP.Common.Common().getNextSequence(EntityName);
                        RoleMapping.RoleMenuMappingId = nextval;
                        RoleMapping.RoleId = permissions.RoleId;
                        RoleMapping.MenuId = rm.Id;
                        RoleMapping.BusinessUnitId = 1;
                        RoleMapping.MenuAdd = (rm.Add == true ? 1 : 0);
                        RoleMapping.MenuDelete = (rm.Delete == true ? 1 : 0);
                        RoleMapping.MenuModify = (rm.Modify == true ? 1 : 0);
                        RoleMapping.MenuView = (rm.View == true ? 1 : 0);
                        RoleMapping.MenuImport = (rm.Import == true ? 1 : 0);
                        RoleMapping.MenuExport = (rm.Export == true ? 1 : 0);
                        RoleMapping.MenuRestrictedView = (rm.RestrictedView == true ? 1 : 0);
                        RoleMapping.MenuBulkUpdate = (rm.BulkUpdate == true ? 1 : 0);
                        RoleMapping.MenuBulkDelete = (rm.BulkDelete == true ? 1 : 0);
                        RoleMapping.MenuSpecial1 = (rm.Special1 == true ? 1 : 0);
                        RoleMapping.MenuSpecial2 = (rm.Special2 == true ? 1 : 0);
                        RoleMapping.MenuSpecial3 = (rm.Special3 == true ? 1 : 0);
                        RoleMapping.MenuSpecial4 = (rm.Special4 == true ? 1 : 0);
                        RoleMapping.MenuSpecial5 = (rm.Special5 == true ? 1 : 0);

                        db.RoleMenuMapping.Add(RoleMapping);
                    }
                }

                db.SaveChanges();

                ViewBag.RoleId = new SelectList(db.Role, "Id", "Code");
                ViewBag.Module = new SelectList(db.Module, "ModuleId", "ModuleName");
                ViewBag.ScreenType = new[] { new SelectListItem { Text = "Select", Value = "select" }, new SelectListItem { Text = "Master", Value = "1" }, new SelectListItem { Text = "Report", Value = "2" }, new SelectListItem { Text = "Transaction", Value = "3" } };

                return View("Index");
            }
        }
        catch (Exception ex)
        {
            Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
            return Json(new { Result = "ERROR", Message = ex.Message });
        }
    }

我认为问题出在这两行

ViewBag.RoleId = new SelectList(db.Role, "Id", "Code");
ViewBag.Module = new SelectList(db.Module, "ModuleId", "ModuleName");

您正在将 DbSet 作为 IEnumerable 传递给 SelectList 构造函数。如果构造函数不迭代传递的枚举而只是存储它,那么 DbContext 超出范围并被释放(由于 using (var db = ...),并且 ObjectDisposedException 将在任何时候抛出DbSet enumerable 被迭代。

我认为您应该确保在处理上下文之前从数据库上下文中使用的所有内容都已具体化。例如,像这样添加 ToList()Select(...).ToList()

ViewBag.RoleId = new SelectList(db.Role.ToList(), "Id", "Code");
ViewBag.Module = new SelectList(db.Module.ToList(), "ModuleId", "ModuleName");