C# – Creating and Disposing Entity Framework DataContext in CRUD Methods

Architecturecdesignwpf

I'm building a wpf application which implements the following features:

  1. Take user input and read data from databases
  2. perform some calculations on it
  3. Showcase it to the user in multiple types of views and write changes back to db

Proposed architecture:
Database -> Entity Framework -> Repository -> Business Logic -> Data Service -> ViewModel

Reasons to use this architecture:
Multiple scenarios present in the application (Multiple views) and multiple databases. Hence, i'm willing to use repository in the middle for abstraction.

One caveat is that the context will be long lived if repository is implemented. To overcome this, is it okay to create a context and dispose them in a using() block in each of the crud methods.?

feel free to suggest alternate approaches.

Best Answer

Use one DbContext object per data access or transaction.

DbContext is a lightweight object; it is designed to be used once per business transaction. Making your DbContext a Singleton and reusing it throughout the application can cause other problems, like concurrency and memory leak issues.

DbContext essentially implements a Unit of Work. Treat it accordingly.

Don't dispose DbContext objects.

Although the DbContext implements IDisposable, you shouldn't manually dispose it, nor should you wrap it in a using statement. DbContext manages its own lifetime; when your data access request is completed, DbContext will automatically close the database connection for you.

To understand why this is the case, consider what happens when you run a Linq statement on an entity collection from a DbContext. If you return a lazy-loading IQueryable from your data access method, you stand up a pipeline that isn't actually executed until the client compels some data from it (by calling FirstOrDefault(), ToList() or iterating over it).

Further Reading
Do I always have to call Dispose() on my DbContext objects?
Why you shouldn't use Singleton DataContexts in Entity Framework
Returning IEnumerable<T> vs. IQueryable<T>
Should Repositories return IQueryable?