How to use Include for objects that are inside a list

Asked

Viewed 165 times

1

I have the following objects in my EF6 context.

public class Produto
{
    public Guid Id {get;set;}
    public string Nome {get;set;}
}

public class VedaItem
{
    public int Item {get;set;}
    public float Valor {get;set;}
    public Guid ProdutoId {get;set;}

    public virtual Produto Produto {get;set;}
}

public class Venda
{
    public DateTime DataVenda {get;set;}
    public string Numero {get;set;}
    public List<VendaItem> Itens {get;set;}

} 

I don’t use Lazyloading, so I need to use Include to access the relationships with Venda to generate a report.

I need to access the Product data you are on VendaItem.

I tried to do the include like this.

var relatorio = contexto.Set<Venda>()
     .Include(v => v.Itens.Produto);
     .Select(v => new 
     {
        NomeProduto = v.Itens.Produto.Nome
     });

But Visualstudio won’t even let me type that: v => v.Itens.Produto.

How do I access data from the Product entity?

1 answer

1


That would be the way:

 var relatorio = contexto.Set<Venda>()
                 .Include(v => v.Itens.Select(p=> p.Produto));

Will return the sales list, with the items and products loaded.

  • 1

    Thank you! I’ll test

Browser other questions tagged

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