1

scaffolding in MVC creates an action like this:

public ActionResult Index()
{
     var users = db.Users.Include(u => u.Roles);
     return View(users.ToList());
}   

in view we use below as a Model :

@model IEnumerable<DataLayer.Users> 

If we eliminate Tolist() in action it works properly. what are benefits of Tolist() that scaffolding uses this? if we eliminate ToList() is it wrong?

CodeNotFound
  • 22,153
  • 10
  • 68
  • 69
MHadi Taghdisi
  • 380
  • 1
  • 4
  • 15
  • 1
    In your case : by removing it you just defer the execution of your query. So the execution will take place on the view when you do `foreach` there. – CodeNotFound Jun 22 '18 at 11:39
  • 1
    The problem would be if the `db` context is disposed of before you iterated the `IEnumerable` then you'd have `ObjectDisposedException` thrown. You should keep the `.ToList()` to avoid that. – Enigmativity Jun 22 '18 at 11:46
  • MVC will [always](https://stackoverflow.com/a/1380062/9695604) dispose the Controller after rendering the View. So the ObjectDisposedException is not in scope here. – bommelding Jun 22 '18 at 12:51

1 Answers1

3

If you let the Tolist() in your controller's action, the query users is executed inside your action. You're passing to your view a model of type List<DataLayer.Users> so because it implements IEnumerable<DataLayer.Users> it works without errors.

If you remove the the Tolist() in your controller's action, the query users is NOT executed inside your action. You're passing to your view a model of type IQueryable<DataLayer.Users> so because it implements IEnumerable<DataLayer.Users> it works without errors. And of course somewhere in your Razor view you're doing a loop like using foreach on your view model so the query is executed there by your view not in the controller's action. Also no exception was thrown because the DbContext is still declared as a field on your controller not locally in your action method so it is still open.

Edit after your comment about which is better?

The better practice is to execute the query (use ToList()) inside your action so the razor view does nothing but reading the result. By doing that you'll get any error related to your query execution inside the action, can catch them and log if you want.

Community
  • 1
  • 1
CodeNotFound
  • 22,153
  • 10
  • 68
  • 69
  • which one is better the query execute inside Action or execute in View? – MHadi Taghdisi Jun 22 '18 at 12:08
  • @MHadiTaghdisi The better practice in your case is to execute the query (use ToList()) inside your action so the view does nothing but reading the result. Also you'll get any error related to your database inside the action and catch them and log them. – CodeNotFound Jun 22 '18 at 12:09