Thursday, March 24, 2011

Should I share the Entity-Framework context or create a new context for each operation?

I'm not that clear on the best-practice concerning the use and re-use of the entity-framework Context.

My question is, should I try to create 1 context and re-use it many times for different queries or should I create a new context for each query?

For example if I have a form with 10 charts all with data queried from the same tables, should the 10 queries be from the one context or 10 different contexts?

From a code encapsulation point-of-view I'd prefer to create 10 new contexts, is this a good idea and is it scalable?

From stackoverflow
  • IMHO - i could be wrong but this is how i do it...

    If you are talking about the Model - Context use one. Since you only need one Model - Context in which to query - ie this is the database model.

    If you are talking about ObjectContext - then one for each Query (Linq). Take alook at this Performance Considerations for Entity Framework

    Rhys : A very good link, it has helped alleviate some fears about performance when creating many contexts.
  • It all depends on your app.

    A key consideration is that ObjectContext is not threadsafe so for a web app ObjectContext per request is the way to go.

    For a Win Forms app you can look at having longer-lived ObjectContexts. However, if you prefer to scope things more tightly I would try that first as opposed to prematurely optimizing it.

    More on Danny Simmons blog here.

    Rhys : Thanks for the link, it provided the information I need to feel comfortable creating different contexts for the situation in my question. Also I had not noticed the Detach method before so that will come in handy for future projects.

0 comments:

Post a Comment