Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法完成操作,因为DbContext已被释放;_C#_Asp.net Mvc_Linq_Asp.net Mvc 4_Elmah.mvc - Fatal编程技术网

C# 无法完成操作,因为DbContext已被释放;

C# 无法完成操作,因为DbContext已被释放;,c#,asp.net-mvc,linq,asp.net-mvc-4,elmah.mvc,C#,Asp.net Mvc,Linq,Asp.net Mvc 4,Elmah.mvc,在运行项目时,我收到以下错误:“操作无法完成,因为DbContext已被释放”。在检查网络时,我看到了许多关于此问题的答案,但我认为我的代码中包含了所有这些。请验证我的代码并让我知道其中的错误,请帮助我。。。 这是在控制器和Elmah中编写的代码,我得到了错误 public ActionResult Create(Permissions permissions) { try { using (var db = new AdminD

在运行项目时,我收到以下错误:“操作无法完成,因为DbContext已被释放”。在检查网络时,我看到了许多关于此问题的答案,但我认为我的代码中包含了所有这些。请验证我的代码并让我知道其中的错误,请帮助我。。。 这是在控制器和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 });
        }
    }
公共操作结果创建(权限)
{
尝试
{
使用(var db=new AdminDb())
{
//删除所选角色的现有权限。。
IList ModuleMenu=(从db.MenuConfig.AsNoTracking()中的d开始)
其中d.ModuleId==permissions.ModuleId
选择d.MenuConfigId.ToList();
var RoleMenu=(来自db.RoleMenuMapping中的c,其中ModuleMenu.Contains((int)c.MenuId)和&c.RoleId==permissions.RoleId选择c.ToList();
foreach(RoleMenu中的var rm)
{
数据库角色映射移除(rm);
db.SaveChanges();//为避免对象处于分离状态错误而添加
}
//向数据库添加新权限
如果(permissions.RoleMenu!=null)
{
foreach(permissions.RoleMenu中的var rm)
{
角色映射角色映射=新角色映射();
//获取下一个ID
字符串EntityName=(db作为IObjectContextAdapter).ObjectContext.CreateObjectSet().EntitySet.Name;
Int32 nextval=new Assyst.PanERP.Common.Common().getNextSequence(EntityName);
RoleMapping.roleemenumappingid=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.MenureRestrictedView=(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.RoleMapping.Add(RoleMapping);
}
}
db.SaveChanges();
ViewBag.RoleId=新的选择列表(db.Role,“Id”,“Code”);
ViewBag.Module=新的选择列表(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”};
返回视图(“索引”);
}
}
捕获(例外情况除外)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
返回Json(新的{Result=“ERROR”,Message=ex.Message});
}
}

我认为问题出在这两行

ViewBag.RoleId = new SelectList(db.Role, "Id", "Code");
ViewBag.Module = new SelectList(db.Module, "ModuleId", "ModuleName");
您正在将
DbSet
s作为
IEnumerable
传递给
SelectList
构造函数。如果构造函数没有迭代传递的可枚举项并只存储它,那么
DbContext
将超出范围并被释放(由于
使用(var db=…
),并且只要迭代
DbSet
可枚举项,就会抛出
ObjectDisposedException

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

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

这个异常具体出现在哪里?哪一行?我不确定错误发生在哪一行,因为Elmah错误日志只是将其显示为错误。实际上,我被要求处理这段代码以找到错误的原因。如果更改
返回Json(new{Result=“error”,Message=ex.Message});
返回Json(新的{Result=“ERROR”,Message=ex.ToString()});
您可能能够显示并使用发生错误的行