Question:
Estou tendo o erro:
Exception Details: System.ObjectDisposedException: The ObjectContext
instance has been disposed and can no longer be used for operations
that require a connection.
Quando faço a chamada:
@Html.DisplayFor(modelItem => item.Cliente.Url)
This view receives a model called boleto, which contains Customers;
I'm doing in the controller :
using (var BolGeral = new BoletoGeral())
{
IEnumerable<boleto> clientesFiltrados = BolGeral.GerarIDCImpressaoMensal();
return View(clientesFiltrados);
}
//se não uso o Dispose ele funciona, pois ai ele ainda está conectado e consegue recuperar os valores.
The function BolGeral.GenerarIDCImpressaoMonsal();
public IEnumerable<boleto> GerarIDCImpressaoMensal()
{
var DataRef = new DateTime(DateTime.Today.Year, DateTime.Today.AddMonths(1).Month, 1);
var IdClientesSemBoleto = (from cli in db.Clientes
join bol in db.Boletos on cli.ClienteId equals bol.ClienteId
where bol.DataReferencia == DataRef && cli.Status == 4 && cli.Convenio == 0
select cli.ClienteId);
var clientes = db.Boletos
.Where(s => !IdClientesSemBoleto.Distinct().Contains(s.ClienteId))
.Where(i => i.Cliente.Status == 4 && i.Cliente.Convenio == 0);
//fazendo o distinct
IEnumerable<boleto> clientesFiltrados = clientes
.Include(i => i.Cliente) // Aqui está o include
.GroupBy(customer => customer.ClienteId)
.Select(group => group.FirstOrDefault()).OrderBy(o => o.Cliente.Url).ToList();
return clientesFiltrados;
}
See that the IEnumerable<boleto> clientesFiltrados
has an include to not do LazyLoad, but why then it gives an error as if doing the LazyLoad, when in the controller I do the next?
Answer:
The Include
statement must come before Where
. IQueryable
assembly can go wrong if you assemble Where
and then use Include
:
var clientes = db.Boletos
.Include(i => i.Cliente) // Aqui está o include
.Where(s => !IdClientesSemBoleto.Distinct().Contains(s.ClienteId))
.Where(i => i.Cliente.Status == 4 && i.Cliente.Convenio == 0);
Also try to materialize the list of clients in memory before assembling the Where
because the Entity Framework tries to solve the list in sentence, and this can generate errors:
var listaDeClientesSemBoleto = IdClientesSemBoleto.Distinct();
var clientes = db.Boletos
.Include(i => i.Cliente) // Aqui está o include
.Where(s => !listaDeClientesSemBoleto.Contains(s.ClienteId))
.Where(i => i.Cliente.Status == 4 && i.Cliente.Convenio == 0);
Lastly:
var clientesFiltrados = clientes
.GroupBy(customer => customer.ClienteId)
.Select(group => group.FirstOrDefault())
.OrderBy(o => o.Cliente.Url)
.ToList();