How can I Include Multiples Tables in my linq to entities eager loading using mvc4 C#
Posted
by
EBENEZER CURVELLO
on Stack Overflow
See other posts from Stack Overflow
or by EBENEZER CURVELLO
Published on 2013-10-30T00:36:54Z
Indexed on
2013/10/30
3:54 UTC
Read the original article
Hit count: 153
I have 6 classes and I try to use linq
to Entities to get the SiglaUF
information of the last deeper table (in the view - MVC). The problem is I receive the following error:
"The ObjectContext instance has been disposed and can no longer be used for operations that require a connection."
The view is like that:
> @model IEnumerable<DiskPizzaDelivery.Models.EnderecoCliente> > @foreach (var item in Model) { > @Html.DisplayFor(modelItem => item.CEP.Cidade.UF.SiglaUF) > }
The query that i use:
var cliente = context.Clientes
.Include(e => e.Enderecos)
.Include(e1 => e1.Enderecos.Select(cep => cep.CEP))
.SingleOrDefault();
The question is: How Can I improve this query to pre loading (eager loading) "Cidade" and "UF"?
See below the classes:
public partial class Cliente
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int IdCliente { get; set; }
public string Email { get; set; }
public string Senha { get; set; }
public virtual ICollection<EnderecoCliente> Enderecos { get; set; }
}
public partial class EnderecoCliente
{
public int IdEndereco { get; set; }
public int IdCliente { get; set; }
public string CEPEndereco { get; set; }
public string Numero { get; set; }
public string Complemento { get; set; }
public string PontoReferencia { get; set; }
public virtual Cliente Cliente { get; set; }
public virtual CEP CEP { get; set; }
}
public partial class CEP
{
public string CodCep { get; set; }
public string Tipo_Logradouro { get; set; }
public string Logradouro { get; set; }
public string Bairro { get; set; }
public int CodigoUF { get; set; }
public int CodigoCidade { get; set; }
public virtual Cidade Cidade { get; set; }
}
public partial class Cidade
{
public int CodigoCidade { get; set; }
public string NomeCidade { get; set; }
public int CodigoUF { get; set; }
public virtual ICollection<CEP> CEPs { get; set; }
public virtual UF UF { get; set; }
public virtual ICollection<UF> UFs { get; set; }
}
public partial class UF
{
public int CodigoUF { get; set; }
public string SiglaUF { get; set; }
public string NomeUF { get; set; }
public int CodigoCidadeCapital { get; set; }
public virtual ICollection<Cidade> Cidades { get; set; }
public virtual Cidade Cidade { get; set; }
}
var cliente = context.Clientes
.Where(c => c.Email == email)
.Where(c => c.Senha == senha)
.Include(e => e.Enderecos)
.Include(e1 => e1.Enderecos.Select(cep => cep.CEP))
.SingleOrDefault();
Thanks!
© Stack Overflow or respective owner