In a winform application, the lifespan/scope of context in Entity Framework 4

entity-framework winforms


Sorry for yet another question about EF4 context lifespan, but I've been wondering about this for a while and I do not seem to find the answer. I'm not very familiar with lots of patterns or overcomplicated stuff (in my point of view) so I want to keep it simple.

I work with an ASP.NET application where the context is managed by each http request which is a very good approach in my opinion.

However I'm now working with a winforms application and I sometimes have transactions or reports that will not perform very well if I simply create the context for each query. Not that this performance issue is a very problematic thing, I just want to hear if there's a simple strategy as per HTTP request in ASP.NET for winforms?

4/14/2011 1:10:24 PM

Accepted Answer

Don't create a context for each query. At the same time, don't create a context that gets used for the entire lifetime of a Form (or your application).

Create a context for a single Unit of Work (which can encompass many queries).

That way you have all of your changes encapsulated in the context and you let Entity Framework wrap the database calls in a pretty little transaction without having to worry about it yourself.

I prefer to abstract the Repository and Unit of Work patterns out of the Entity Context so that I can use them independently (which makes everything very clear). MSDN actually has a decent article on the details:

MSDN - Using Repository and Unit of Work patterns with Entity Framework 4

4/14/2011 1:11:58 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow