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.