Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 371
Rhys Avatar asked Jan 19 '09 11:01

Rhys


People also ask

Which approach is best in Entity Framework?

As in this diagram, if we already have domain classes, the Code First approach is best suited for our application. The same as if we have a database, Database First is a good option. If we don't have model classes and a database and require a visual entity designer tool then Model First is best suited.

What is the difference between DbContext and DbSet?

Intuitively, a DbContext corresponds to your database (or a collection of tables and views in your database) whereas a DbSet corresponds to a table or view in your database. So it makes perfect sense that you will get a combination of both!

Is DbContext scoped or transient?

This example registers a DbContext subclass called ApplicationDbContext as a scoped service in the ASP.NET Core application service provider (a.k.a. the dependency injection container). The context is configured to use the SQL Server database provider and will read the connection string from ASP.NET Core configuration.

How does DbContext work in Entity Framework?

As per Microsoft “A DbContext instance represents a session with the database and can be used to query and save instances of your entities. DbContext is a combination of the Unit Of Work and Repository patterns.” In simplified way we can say that DbContext is the bridge between Entity Framework and Database.


1 Answers

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.

like image 83
Andrew Peters Avatar answered Oct 05 '22 18:10

Andrew Peters