Given:
public ActionResult List()
{
using (var unitOfWork = new UnitOfWork())
{
var result = unitOfWork.Repository.Find&l
Lazy and eager loading have to do with when entities related to your query (e.g. navigation properties and collections) are loaded, not when the contents of the query itself are loaded.
The IQuerable<EntityAddress>
returned from your repository—whether or not you have lazy loading enabled—will not run the query on the server until it's enumerated (whether that's by getting an enumerator in a foreach
loop, calling Enumerable.ToList<TSource> on it, or passing it into a call to Controller.View for downstream rendering).
The reason you get an exception in this case is because Controller.View does not immediately render the view (and therefore does not immediately enumerate the query). All it does is construct an instance of ViewResult that holds onto the model parameter (your query object) until MVC does render the view later on, after you've disposed your context.
If you want to pass query results to a view, you have two options:
IQuerable<EntityAddress>
before the database context is disposed, and use the resulting List<EntityAddress>
instead of the IQuerable<EntityAddress>
.