1

I think there is two main ways (or more) to define Entity framework Context:

  1. Define one Context in the whole App and then use it during all it's life cycle, so here the Context will be disposed after closing the app, I defined this variable in MainWindow then I used it in all my app windows and User Conteols

    public static SC_Context Context = new SC_Context();

  2. Define the context every time we want to deal with the database and dispose that context after that. In this way, I make partial classes and write method inside:

    using (SC_Context Context = new SC_Context()) { //Bla Bla Bla }

Actually, I used both ways in many apps, Websites and Windows apps and I saw many samples and developers using them.

Simply my question is: Which is better -using one context for whole app or use one context for each procedure with DB- for App performance and RAM consumption and Why?

JRB
  • 1,943
  • 1
  • 10
  • 9
  • 1
    Marked as duplicate, but apart from that this question is too opinion-based for Stack Overflow. That said, the best I've ever read about this is [this](http://mehdi.me/ambient-dbcontext-in-ef6/). – Gert Arnold May 08 '16 at 19:46

1 Answers1

1

According to MSDN (or this blog), you should use the second way, with using statement. When you use using, the compiler automatically creates a try/finally block and calls dispose in the finally block.

Here are some general guidelines when deciding on the lifetime of the context:

  1. When working with Web applications, use a context instance per request.
  2. When working with Windows Presentation Foundation (WPF) or Windows Forms, use a context instance per form. This lets you use change-tracking functionality that context provides.

In conclusion, the rule is: context per request and context per form lifetimes.

Triet Doan
  • 11,455
  • 8
  • 36
  • 69