lambinator
lambinator

Reputation: 11009

DbContext "using" in a single line

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..

Upvotes: 5

Views: 12417

Answers (3)

Marco Staffoli
Marco Staffoli

Reputation: 2496

DbContext manages the underlying connection for you.
You can call Dispose, but in most common scenarios you don’t need to.

http://blog.jongallant.com/2012/10/do-i-have-to-call-dispose-on-dbcontext.html

Upvotes: 0

Chris Shain
Chris Shain

Reputation: 51339

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):

public static class MyDbContextStatic { 
    public static T Execute(Func<MyDbContext, T> f) {
        using (var db = new MyDbContext())
            return f(db);
    }
}

To use:

var users = MyDbContextStatic.Execute(db => db.Users);

IIRC, you probably want to call Detach or something on each object before disposing the DbContext as well. But you get the idea.

Upvotes: 5

Habib
Habib

Reputation: 223277

Your first example is the proper way to do it, it makes sure to call Dispose after the end of the block, that will cause the connection to be closed. You may comeup with an extension method to do your work, But it will require you to have a reference to DbContext in memory for static DbContext.

With respect to database connection, you should open them as late as possible and close as early as possible.

Upvotes: 2

Related Questions