Question

I have 2 classes, and try to use the reference in view of a class to another class gives the error:

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

Class "CLIENTE"

public class Cliente : IEntidadeBase
{
  [Key]
  [Display(Name = "Cód. de Cliente")]
  public int ClienteID { get; set; }
  [Display(Name = "Cód. de Pessoa")]
  public int PessoaID { get; set; }
  public string Matriz { get; set; }

  [Display(Name = "Limite de crédito")]
  public decimal LimiteCredito { get; set; }

  [ForeignKey("PessoaID")]
  public virtual Pessoa Pessoa { get; set; }
}

Class "PESSOA"

public class Pessoa : IEntidadeBase
{
  [Key]
  public int PessoaID { get; set; }
  public int? EmpresaIDVinc { get; set; }

  [Display(Name = "Matrícula")]
  public string Matricula { get; set; }

  [Display(Name = "Nome")]
  [Obrigatorio]
  public string Nome { get; set; }
}

Controller View change:

[Authorize]
[ControleDeAcesso(TipoAcao.Normal)]
public ActionResult Detalhar(int id)        
{
    using (var db = new ERPContext())
    {
        Cliente cliente = db.Cliente.Find(id);
        var retorno = FlexGestor.Helpers.EntidadeBaseExt.ValidarRegistro(cliente, TipoAcao.Visualizar);
        if (retorno != "")
        {
            TempData["MsgRetornoError"] = retorno;
            return RedirectToAction("Index", "Home");
        }
        return View(cliente);
    }
}

View Code:

@model FlexGestor.Models.Cliente

@Html.TituloPagina("Visualizando Cliente")


@using (Html.BeginForm())
{
    @Html.ValidationSummary(true);

    <div class="linha left">
        @Html.HiddenFor(m => m.ClienteID)

        @Html.LabelFor(m => m.Pessoa.Nome) @Html.ValidationMessageFor(m => m.Pessoa.Nome)<br />
        @Html.TextBoxFor(m => m.Pessoa.Nome, new { style = "width:250px;" })<br />

        @Html.LabelFor(m => m.LimiteCredito) @Html.ValidationMessageFor(m => m.LimiteCredito)<br />
        @Html.TextBoxFor(m => m.LimiteCredito, new { style = "width:250px;" })<br />

        @Html.BotaoTelaDetalhar()        
    </div>    
}

<div class="linha rodape"></div>
Was it helpful?

Solution

I'm not 100% sure if this will fix your issue but try changing to this and see if it helps

[Authorize]
[ControleDeAcesso(TipoAcao.Normal)]
public ActionResult Detalhar(int id)        
{
    Cliente cliente = null;
    using (var db = new ERPContext())
    {
        cliente = db.Cliente.Find(id);
        var retorno = FlexGestor.Helpers.EntidadeBaseExt.ValidarRegistro(cliente, TipoAcao.Visualizar);
        if (retorno != "")
        {
            TempData["MsgRetornoError"] = retorno;
            return RedirectToAction("Index", "Home");
        }
    }

    if(cliente != null && cliente.pessoa != null)
    {
        return View(cliente);
    }
    else
    {
        // do something else here as the view does not have required stuff
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top