14

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?

johnildergleidisson
  • 2,087
  • 3
  • 30
  • 50

1 Answers1

19

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

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • & @dotnedify - Thanks for this, I'm looking at doing this exact same thing for our wretched DataSet driven forms. Upvotes for all. – Tom Apr 14 '11 at 13:24
  • I got the idea. My problem is I was creating static classes with static methods to handle methods such as Insert/Update/Get and the result is having to pass context for every function instead of creating an instance of a Manager class and passing it to the class level. Thanks it really opened my eyes! – johnildergleidisson Apr 14 '11 at 14:37
  • @Tom - glad i indirectly helped, for once! – johnildergleidisson Apr 14 '11 at 14:38
  • i am not good with the terminologies in programing, do you mean its good to use using(contxt = new contxtDBEntities()){somthing to do with} – r.hamd Aug 20 '15 at 17:06