Entity Framework. Select only 1 from a list in Include?

Asked

Viewed 145 times

0

I’m only trying to get a 1 record of the Phones and Emails lists.

var lista = Db.Oportunidades
    .Include(x => x.Conta.Proprietario)
    .Include(x => x.Conta.Contatos.Select(c => c.Telefones))
    .Include(x => x.Conta.Contatos.Select(c => c.Emails))
    .Include(x => x.Estado)
    .Include(x => x.Motivo)
    .Include(x => x.Tipo);

I’ve tried to use First(), Sigle(), Take(1) that generate the error below.

The Include path Expression must refer to a navigation Property defined on the type. Use dotted paths for Reference navigation properties and the Select Operator for Collection navigation properties. Name of parameter: path

Any hint?

  • 1

    I believe this link can help you: https://stackoverflow.com/questions/38676029/the-include-path-expression-must-refer-to-a-navigation-property-defined-on-the-t

  • 1

    You probably have to use something like this: var list = Db.Opportunities . Include(x => x.Conta.Proprietary) . Include(x => x.Conta.Contacts) . Include(x => x.Status) . Include(x => x.Reason) . Include(x => x.Type) . Select(c => new { Phone = x.Conta.Contacts.Select(c => c.Phones). First(), Email = x.Conta.Contacts.Select(c => c.Emails). First(), }). Tolist();

1 answer

0


It is impossible. The function Include does not support these types of operations.

You can use the Select and return an anonymous type containing the main record, phone and email.

Example:

var lista = Db.Oportunidades
    .Include(x => x.Conta.Proprietario)
    .Include(x => x.Estado)
    .Include(x => x.Motivo)
    .Include(x => x.Tipo)
    .Select(x => new 
    {
        Registro = x,
        Telefone = x.Conta.Contatos.Telefones.FirstOrDefault(),
        Email = x.Conta.Contatos.Emails.FirstOrDefault(),
    });
  • Thank you. I was trying not to do so because I will have to change the return, which today already expects a list of opportunities, and consequently the objects that await it. Vlw

Browser other questions tagged

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