简体   繁体   中英

How can i access an object in a list in c# query with ef?

So I´m having a problem with a query im trying to do. I´m trying to get the last element of a list in a linq query in c# using ef.

Here is the code im trying to execute:

 public List<Viagem> getViagensToBeCompletedInBlocoTrabalho()
 {
     return this.context.Viagens
        .Where(v => v.blocosTrabalho.Count() == 0
          || !v.blocosTrabalho.LastOrDefault().noFim.Equals(v.horasPassagem.LastOrDefault().codigoNo)
        )
        .ToList();
 }

But i get this error: Queries performing 'LastOrDefault' operation must have a deterministic sort order. Rewrite the query to apply an 'OrderBy' clause on the sequence before calling 'LastOrDefault'.

What am i doing wrong here?

By the way the sorting that i want is the order of entries in the table so i don´t really want to sort anything. Although i have also tested sorting and it doesn´t work.

Thanks for the help in advance:-)

Actually SQL standard do not support retrieving records from the end and even do not guarantee records in concrete order. EF is trying to simulate that by correcting OrderBy operator and if you do not specify that - it will fail.

Consider to rewrite your query and make it performant:

public List<Viagem> getViagensToBeCompletedInBlocoTrabalho()
{ 
    var query =
       from v in this.context.Viagens
       from b in v.blocosTrabalho.OrderByDescending(x => x.Id)
          .Take(1).DefaultIfEmpty()
       from h in v.horasPassagem.OrderByDescending(x => x.Id)
          .Take(1).DefaultIfEmpty()
       where
          b == null || b != null && b.noFim == h.codigoNo
       select v;

     return query.ToList();
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM