Include in the Entity Framework from an Enumerable

2

I have the following entities:

public class Rota
{
    public Rota()
    {
        CidadesRotas = new List<CidadesRota>();
    }
    public int RotaId { get; set; }
    public string Descricao { get; set; }
    public string Observacao { get; set; }
    public bool Ativo { get; set; }
    public virtual ICollection<CidadesRota> CidadesRotas { get; set; }

}

public class Cidade
{
    public Cidade()
    {
        CidadesRotas = new List<CidadesRota>();
    }
    public int CidadeId { get; set; }
    public string Nome { get; set; }
    public virtual Estado Estado { get; set; }
    public virtual ICollection<CidadesRota> CidadesRotas { get; set; }
}




public class CidadesRota
{
    public int CidadeId { get; set; }
    public int RotaId { get; set; }
    public bool Ativo { get; set; }
    public Cidade Cidade { get; set; }
    public Rota Rota { get; set; }
}

When I perform a route search for an Id, I need each item in my list of CitiesRota to be populated with their respective cities. I know it's meant to use Entity's Include, but I'm not sure how to use it from an item in a list.

In the following example, I get back a route with a list of citiesRota:

var query = _context.Rota
            .Include(r => r.CidadesRotas)
            .Where(r => r.RotaId == RotaId);

Doubt: Is it possible to bring each item from the list of citiesRotas with their respective cities filled out?

    
asked by anonymous 23.08.2018 / 21:20

1 answer

2

Yes! It's possible! Just use ThenInclude:

var query = _context.Rota
        .Include(r => r.CidadesRotas)
            .ThenInclude(r => r.Cidade)
        .Where(r => r.RotaId == RotaId);

It may be that your IntelliSense issues a problem, but it's an IntelliSense bug that can be tracked here: link

You can try to build which will succeed. :)

    
23.08.2018 / 21:29