If you create a WebAPI/MVC project in say Visual Studio 2013, add Model (and DbContext class), and a Controller for this model as outlined here-
http://www.asp.net/web-api/overview/data/using-web-api-with-entity-framework/part-2,
it creates a controller that declares the DbContext as a member variable, which is according to many stackoverflow answers/online arcticles, is a bad idea- like this one
https://stackoverflow.com/a/10588594
The controller methods generated by Visual Studio-
// GET: api/Authors
public IQueryable<Author> GetAuthors()
{
return db.Authors;
}
Will not work if you use the recommended per request lifetime -
// GET: api/Authors
public IQueryable<Author> GetAuthors()
{
DbSet<Author> authors = null;
using(MyContext db = new MyContext) {
authors = db.Authors;
}
return authors;
}
Because the context is out of scope by the time the result is iterated over and you get an object disposed exception.
So, what's the correct way and if it is the "using" per request method, why does the VS template use the member variable method?