首页 文章

如何解决“ObjectContext实例已被处理,不能再用于需要连接的操作”以应对奇怪的情况

提问于
浏览
0

我知道如何解决这个问题,但是,这个错误出现在与我完全不同的情况中 .

在我的MVC Razor视图中,我有以下代码将过滤模型列表,并根据登录的用户以及结果不同于null的字段向我提供特定对象:

@{
    Models.PostOrcamentoServicoProposta proposta = Model.PostOrcamentoServicoProposta.FirstOrDefault(p => p.Usuarios.UsuEmail.Equals(User.Identity.Name, StringComparison.OrdinalIgnoreCase) && p.PosOrcSerProStatus != null);
    if (proposta != null)
    {
      // create a div here
    }
}

在我的 ActionResult 中,我有以下负载

using (ServiciliEntities db = new ServiciliEntities())
{
   // include data
   PostOrcamentoServico orcamento = db.PostOrcamentoServico.Include("PostOrcamentoServicoProposta").Where(o => o.PosOrcSerId == id).FirstOrDefault();
   return View(orcamento);
}

我们可以看到,在我的视图中,我收到一个包含 PostOrcamentoServicoProposta 列表的模型,我希望根据用户登录只获得一个特定的 PostOrcamentoServicoProposta item .

没问题,但我也希望 where PosOrcSerProStatus 不应该为空 .

并且存在问题,这个领域 PosOrcSerProStatus .

PosOrcSerProStatus 字段是 Nullable<Enumerable> ,有时可能可以为空 .

所以,当我调试我的视图时,我可以看到 PosOrcSerProStatus 为空,并且,'s okay to me, however, even if I' m试图操纵只得到条件为p.PosOrcSerProStatus!= null的那个不可为空的那个,然后,我得到了错误:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection

First :PosOrcSerProStatus列表填充在Include("PostOrcamentoServicoProposta")的操作中;

Second :Model.PostOrcamentoServicoProposta包含对象;

Third :在所有 PostOrcamentoServicoProposta 对象中,它们已正确填充,PosOrcSerProStatus可以是或不可以为空 .

1 回答

  • 0

    我认为你的问题是 PosOrcSerProStatus 是一个子关系, Nullable<Enumerable> 对实体框架没有意义 . 如果实体框架想要执行 .Include() ,它会尝试实例化它而不能因为它是null . 只需尝试像这样创建 PosOrcSerProStatus 虚拟,看看它是否已经解决 .

    // Instantiate your class and at the same time make PosOrcSerProStatus a new list
    public PostOrcamentoServicoProposta()
    {
      PosOrcSerProStatuses = new List<PosOrcSerProStatus>();
    }
    
    // Also make PosOrcSerProStatuses a virtual ICollection
    public virtual ICollection<PosOrcSerProStatus> PosOrcSerProStatuses { get; set; }
    

    我能想到的另一件事就是你在View中执行查询之前关闭了DbContext ...即 . 您在 ActionResult 中使用了 using() ,当它到达视图并且您尝试执行 FirstOrDefault() 查询时,DbContext已经关闭 .

相关问题