I find myself doing this a lot:
using(var db = new MyDbContext())
{
return db.Users.ToList(); // or some other simple query
}
It would be nice to these simple cases as something like:
return MyDbContext.Execute(db => db.Users);
but I’m not sure how I would do the extension method. Ideally (i think) it would take a DbContext (so I could reuse the code) and return the templated IList.. but is this possible?
Of course, if there’s already a method that does this I would love to hear about it..
You could write the simplest of static classes for this. You don’t want an extension method, because that requires an instance (and based on the syntax in your example, you don’t yet have one):
To use:
IIRC, you probably want to call Detach or something on each object before disposing the DbContext as well. But you get the idea.