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?