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

本文关键字:释放 DbContext 因为 操作 | 更新日期: 2023-09-27 18:26:26

在运行项目时收到此错误"操作无法完成,因为DbContext已被处理"。在检查网络时,我看到了许多关于此问题的答案,但我认为我的代码中都有。请验证我的代码,让我知道其中有什么错误,请帮助我。。。这是写在控制器和Elmah am中的代码得到的错误。

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

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

我认为问题出在的这两行

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

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

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

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