Returned list sorted in BLL?

1

In my project I use EF6 , I use generic repositories and in my BLL layer I have the ClienteBLL class, which is a class that has the logical implementation methods of the class.

In one of the methods I return a list that receives all the clients of the bank and then makes an ordering

Method:

public IList<ClienteDTO> TodosClientes()
{
   List<ClienteDTO> lista = clienteRepo.BuscarTodos().ToList();    
   lista.Sort(delegate (ClienteDTO a, ClienteDTO b) { return a.nome.CompareTo(b.nome); });

   return lista;
}

My question: Is it wrong to sort the list in this way? If so, what do you recommend?

I found it a much better way: How to sort the list by a property in the object

So based on the response of the link I did so:

public IList<ClienteDTO> TodosClientes()
{
    return clienteRepo.BuscarTodos().OrderBy(o => o.nome).ToList();
}

Now I have no doubt that it's right!

My generic repository:

public abstract class GenericRepository<T> : IDisposable, IGenericRepository<T> where T : class
    {
        GdPContext contexto = new GdPContext();


        public IQueryable<T> BuscarTodos()
        {
            IQueryable<T> query = contexto.Set<T>();
            return query;
        }

        public IQueryable<T> Buscar(Expression<Func<T, bool>> predicado)
        {
            IQueryable<T> query = contexto.Set<T>().Where(predicado);
            return query;
        }

        public void Adicionar(T entity)
        {
            contexto.Set<T>().Add(entity);
        }

        public void Excluir(T entity)
        {
            contexto.Set<T>().Remove(entity);
        }

        public void Editar(T entity)
        {
            contexto.Set<T>().AddOrUpdate(entity);
        }

        public void Salvar()
        {
            contexto.SaveChanges();
        }

        public void Dispose()
        {
            contexto.Dispose();
        }
    }
    
asked by anonymous 24.08.2018 / 22:28

1 answer

1

In the implementation of your class of interface ( IGenericRepository<T> ) create another method with the following signature:

IQueryable<T> BuscarTodos<Tkey>(Expression<Func<T,Tkey>> orderBy);

and soon after implementing in your class GenericRepository<T> , within the method make the following code that is ideal and the ordering made direct in the SQL statement and the data coming from your table :

public IQueryable<T> BuscarTodos<Tkey>(Expression<Func<T, Tkey>> orderBy)
{
    return contexto.Set<T>()
                   .AsNoTracking()
                   .OrderBy(orderBy); 
}

To use this code:

clienteRepo.BuscarTodos(o => o.nome).ToList();

The method that was added AsNoTracking() is another optimization, where the returned data will only be read and not kept in context, ie the data is read-only, this is good for displaying data that will not be changed at that time .

    
25.08.2018 / 03:56