doubt with Entity and limit

Asked

Viewed 53 times

1

I need to retrieve the last 100 records from the bank, I’m using the code below, but it returns the first 100:

 dynamic data = null;
        try
        {
            data = limit == 0 ?
                (from p in contexto.Set<TEntity>() select p).Where(predicate).ToList() :
                (from p in contexto.Set<TEntity>() select p).Where(predicate).ToList().Take(limit);

        }

I tried to put . Last(), but gave an error: inserir a descrição da imagem aqui

how can I fix this ?

1 answer

0

Error:

A conversion error is happening List<TEntity> for TEntity, they are different and conversion is necessary. The Last() returns the last element on the list, and actually needs the 100 last elements, saw the difference?

Fact:

I’m searching the Bank’s last 100 records (ORDER BY CAMPO DESC)

So:

Sorts your SQL by key field (Orderbydescending) bring the 100 first records who actually are the last 100 record.

var lista = (from p in contexto.Set<TEntity>() select p)
             .Where(predicate)
             .OrderByDescending(orderByPredicate)
             .Take(limit)
             .ToList();

Observing: when you put ToList() and then Take(100) brought all the records and then took 100, This is a big mistake, make the SQL bring only the 100 records, as shown in the example.

After that if you need to Orderly in the List of Objeto, as I have already brought the 100 last registration and is in memory do so (any filter, ordering, etc.):

lista.OrderBy(predicate);

Browser other questions tagged

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