4
In one of the projects I picked up I saw the following code, which implements a data listing method of a given entity, but this listing is used only for reading:
/// <summary>
/// Listar todas entidades
/// </summary>
/// <returns></returns>
public IList<T> ListarTodos()
{
return ctxContexto.Set<T>().ToList();
}
The method works perfectly, my doubt is about performance and good programming practices with Entityframework. A while ago I saw a question here at Sopt that talked about difference between Ienumerable, Iqueryable and Ilist.
Based on the above-mentioned question, I thought "If my method returns a List<T>
I will be giving the person who calls the method the possibility 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, again every time I call the Listed 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 presented by Resharper.
Possible Multiple enumeration of Ienumerable
This has also been dealt with in a question here from Sopt and I understood why of the same, my doubts are:
What is the best approach in this case?
Some of them will bring me some performance benefit?
"(which I don’t understand, because a list can be changed within the flow of a request)". I may not have expressed myself well, but the context of my application requires this piece to be read-only. In my case it is a rule of my business.
– Julio Borges
Then use a read-only list. If
List<>
can be changed, it is not the data structure you need.– Leonel Sanches da Silva
I disagree with my friend @cigano-Morrison-Mendez, because List is a Class where implements all these interfaces: Ilist<T>, Icollection<T>, Ienumerable<T>, Ienumerable, Ilist, Icollection, Ireadonlylist<T>, Ireadonlycollection<T>
– Maurício Júnior