Include Entityframework

Asked

Viewed 149 times

3

I am working with Entity Framework 6, I have made all the necessary settings. I have a Class Person that owns a Property of the Address Type, within address I have a property Municipality that ultimately has a property of the Type UF. I have a function that I need to recover all registered people and display on a grid, so far so good, but the data of the objects that are part of my person class, is not loaded. I used that code:

 _dbcontext.Pessoas.Include(x => x.Endereco.Municipio.Uf).ToList();

When I debug the project Entityframework generates Sql correctly, I copy the sql and run in sqlserver, the data is displayed in the way I expected, but the information that the Entity brings from the database is not included in the properties of my person class, only the data existing in the person table and that are loaded.

  • Is there any way you can put the models in your question?

2 answers

3

That is to say:

public class Pessoa 
{
    [Key]
    public int PessoaId { get; set; }
    public int EnderecoId { get; set; }

    public virtual Endereco Endereco {get; set;}
}

public class Endereco
{
    [Key]
    public int EnderecoId { get; set; }
    public int MunicipioId { get; set; }

    public virtual Municipio Municipio { get; set; }
}

public class Municipio
{
    [Key]
    public int MunicipioId { get; set; }
    public int UfId { get; set; }

    public virtual Uf Uf { get; set; }
}

Change:

_dbcontext.Pessoas.Include(x => x.Endereco.Municipio.Uf).ToList();

To:

_dbcontext.Pessoas.Include("Endereco.Municipio.Uf").ToList();

Or else:

_dbcontext.Pessoas
    .Include(x => x.Endereco)
    .Include(x => x.Endereco.Select(e => e.Municipio))
    .Include(x => x.Endereco.Municipio.Select(m => m.Uf))
    .ToList();
  • I tried the first solution you suggested, it still didn’t work. The second it doesn’t even compile, it shows an error in . Include(x => x.Endereco.Select(e => e.Municipio))

0

try this one

_dbcontext.Pessoas.Include("Endereco", "Endereco.Municipio", "Endereco.Municipio.Uf").ToList();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.