EntityFramework .AsEnumerable () or .ToList ()?

4

In one of the projects I got I saw the following code, which implements a data-listing method of a given entity, but this listing is read-only:

/// <summary>
/// Listar todas entidades
/// </summary>
/// <returns></returns>
public IList<T> ListarTodos()
{
    return ctxContexto.Set<T>().ToList();
}

The method works perfectly, my question is regarding performance and good programming practices with EntityFramework. Some time ago I saw a question here in SOpt that spoke of difference between IEnumerable, IQueryable and IList .

Based on the above question, I thought, "If my method returns a List<T> , I'll be giving the caller the ability to insert or remove items from the list," which is not correct, since my list is read-only.

List<Cliente> lista = new Servico<Cliente>().ListarTodos();
lista.RemoveAt(0)
lista.Add(new Cliente());

I changed the method return to IEnumerable as below:

/// <summary>
/// Listar todas entidades
/// </summary>
/// <returns></returns>
public IEnumerable<T> ListarTodos()
{
    return ctxContexto.Set<T>().AsEnumerable();
}

The above code also worked, most every time I call the ListAll method, if I perform more than one check with the list item in the same code context:

List<Cliente> lista = new Servico<Cliente>().ListarTodos();
int count = lista .Count();
Console.WriteLine(count);
Console.WriteLine(lista .Any());

The message is displayed by Resharper.

  

Possible multiple enumeration of IEnumerable

This has also been addressed in a question here from SOpt and I understood why, my doubts are:

What is the best approach in this case?

Will any of them bring me some performance benefit?

    
asked by anonymous 03.08.2016 / 20:23

2 answers

3
  

What is the best approach in this case?

Continue to use List<> , which is the in-memory resolution of an enumeration. An enumeration can be a function or method whose performance is worse.

If you want the list to be read-only (which I do not understand, because a list can rather be changed within the stream of a request), you should use AsReadOnly() :

/// <summary>
/// Listar todas entidades
/// </summary>
/// <returns></returns>
public IReadOnlyCollection<T> ListarTodos()
{
    return ctxContexto.Set<T>().ToList().AsReadOnly();
}
  

Will any of them bring me some performance benefit?

The way you're using it, no. Use repository over repository, beyond unjustified , brings unnecessary performance penalties.

    
03.08.2016 / 20:31
-1

List is a class where you implement all of these interfaces:

IList, ICollection, IEnumerable, IEnumerable, IList, ICollection, IReadOnlyList, IReadOnlyCollection

  • To iterate only once with the result, use the IEnumerable or IReadOnlyCollection interface
  • For more than one iteration, convert your enumerable to list: .ToList() at the beginning of the method scope where the IEnumerable return method is called
  • I hope I have helped!

        
    04.08.2016 / 01:56