ObjectContext实例已被释放

时间:2013-05-07 12:19:22

标签: entity-framework frameworks entity

我正在使用.Net 4.0 EF 4.0。

我在数据库myentity,mygroup和myapplication中有三个表。 myentity可能属于1到更多mygroups,并且有1到更多myapplications并映射到EF。然后我有一个myentityrepository类公开一个方法:

    public MyEntity GetByName(string name)
    {
        var v = Set().Where(x => x.Name == name)
            .Include(x => x.MyEntityMyApplications)
            .Include(x => x.MyEntityMyGroups);
        v.Load();
        //v.ToList();

        return v.FirstOrDefault();
    }

在我的MVC controller.cs中,我获取了Name并使用myentity对象填充了我的viewmodel。返回到视图页面后,我收到了上面的错误。

     [HttpGet]
     public ActionResult GetMyentityAjax(string name)
     {
          MyViewModel uvm = new MyViewModel();
        using (IUnitOfWork unitOfWork = new UnitOfWork(new MyentityEntityContextFactory()))
        {
             Myentity me = _myentityRepository.GetByName(name);

            if (me != null)
            {
                uvm.Name = me.Nme;
                 ...                      
                 uvm.MyentityMyApplication = me.MyentityMyApplication.ToList();
                uvm.MyentityMygroups = me.MyentityMygroups .ToList();
            }
        }
        return Json(uvm, JsonRequestBehavior.AllowGet);         }
      //Even turned the lazyloding to false in //MydataModel.designer.cs as below
     public MyappEntities() : base("name=MyappEntities", "MyappEntities")
      {
        //#### CHANGE ME ######
        //this.ContextOptions.LazyLoadingEnabled = true;
        this.ContextOptions.LazyLoadingEnabled = false;
        //#### END #####
        OnContextCreated();
      }

请帮忙。 TIA,
-t

1 个答案:

答案 0 :(得分:0)

在mydatamodel.designer.cs中将所有三个this.ContextOptions.LazyLoadingEnabled更改为false后,异常消失了。