I have several actions in my controllers that return an IEnumerable of the EF entities.
I was thinking on making these actionmethods return a list instead (just calling a model.ToList() before passing it back to the view).
There are two reasons why I’m thinking on doing that:
- First, I’m measuring the performance of each one of the actionmethods in the BaseController class (onactionexecuted/onactionexecuting) and if I return an IEnumerable then the query isn’t executed until after the onactionexecuted method.
- Second, I was planning on disposing the connections used by my “services layer” inside OnActionExecuted, however if I dispose them there, the views fail bc of the models not being retrieved.
My question is, are any drawbacks of doing this?
I’m pretty sure that every IEnumerable Model will be traversed completely, so it won’t be a problem retrieving data that won’t be used.
Thanks for your help.
This is a perfectly valid thing to do IMO. You pretty much already pointed out the pros and cons. The main difference is that .ToList is loaded into memory all at once, while the other allows for an on-demand load.
If you are planning to load the entire enumeration anyway, then calling .ToList will save you bandwidth by requesting everything in one grab instead of one at a time. So, if anything this sounds like it might be a better path anyway.