Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC2 with Entity Framework 4 - AsEnumerable() or ToList() in repository?

So I've been advised a few times to disable lazy loading when building an application with the above frameworks, and that ToList() will force the queries in my repository to execute. I was told that I would avoid certain "traps" I might run into if I used AsEnumerable().

On a recent question, however, I included a bunch of ToList()s in my code examples, and startled a number of people that assured me IEnumerable is much better to return.

I'm thoroughly confused now, to say the least.

Should I be returning IEnumerable in my repository, then converting them to List in my view models? Should I use ToList() straightaway in my repository like I was before? Was I suppose to leave deferred execution enabled in the first place?

Jiminy Christmas...

Edit: So, being that I disabled lazy loading, based on earlier advice, should I then re-enable it, return IEnumerable / IQueryable from my repository, and convert the collection to a List in my view models, if needed?

One of the answers below associates IEnumerable with eager execution, while I was under the impression that only ToList() would force immediate execution of the query.

I stumbled across this, this, and this that all contain some interesting discussion related to this question.

like image 850
asfsadf Avatar asked Sep 23 '10 03:09

asfsadf


People also ask

Do we need repository pattern with Entity Framework?

No, the repository/unit-of-work pattern (shortened to Rep/UoW) isn't useful with EF Core. EF Core already implements a Rep/UoW pattern, so layering another Rep/UoW pattern on top of EF Core isn't helpful.

How retrieve data from database in MVC 5 without Entity Framework?

Database connection without Entity FrameworkOpen Visual Studio 2015 or an editor of your choice and create a new project. Choose the "web application" project and give an appropriate name to your project. Select "empty" template, check on MVC checkbox and click OK.

What is repository layer in MVC?

The repository layer isolates Business layer from the Data Access Layer. The Repository contains Data Mapper entity. This entity can be used as a model entity for providing schema of the data for performing CRUD operations, by using the CRUD operations defined in the repository.


1 Answers

Call ToList(), returning an IEnumerable in your repository, if:

  1. You want to control the output set provided to the consumer (i.e. you don't want them to run queries on it), and
  2. You don't mind eager execution.

Return IQueryable, or IEnumerable via AsEnumerable(), in your repository if:

  1. You don't mind your consumers running queries on the output set, and
  2. You want deferred execution.

See Also
http://thinkbeforecoding.com/post/2009/01/19/Repositories-and-IQueryable-the-paging-case

like image 68
Robert Harvey Avatar answered Sep 26 '22 01:09

Robert Harvey