Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are queries executed on DbContext

I am trying to understand the performance impact of having one DbContext class vs multiple when using EF6 framework.

For example, if we have a simple DbContext such as this:

public class MainDbContext : DbContext
{
    public DbSet<Car> Cars { get; set; }

    public void AddCar(Car car)
    {
        Cars.Add(car);
        SaveChanges();
    }
}

Now let us say I have a service that uses the said DbContext in the following way:

public class CarService
{
    public List<Car> Cars { get; private set; }
    public CarService()
    {
        var dbContext = new MainDbContext();
        Cars = dbContext.Cars.ToList();
    }
}

At what point in time did the DbContext go to the database and retrieved all cars that are stored in the database? Was it when I called var dbContext = new MainDbContext(); or was it when I called Cars = dbContext.Cars.ToList();?

If former, if I had a DbContext that contains 100 tables, will all 100 tables be queried when the DbContext is created?

like image 244
Bagzli Avatar asked May 30 '17 21:05

Bagzli


People also ask

When the LINQ query is executed?

LINQ queries are always executed when the query variable is iterated over, not when the query variable is created. This is called deferred execution. You can also force a query to execute immediately, which is useful for caching query results. This is described later in this topic.

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.

Can multiple queries be run on single DbContext instance at the same time?

Now following analogy that only single DbContext instance can run one SQL command, we'll organize our code in controller v2 in a way to create instance of DbContext for each command and therefore execute each one in a separate task.


1 Answers

No. The query happens once you enumerate a table. Even in your second example, it still does not connect to the database.

It will connect when you enumerate, for example:

dbContext.Cars.ToList();

Or

foreach (Car c in dbContext.Cars)

Or bind the table to a UI control.

However when you make a where, order by, then by, join etc.. e.g.

var result = dbContext.Cars.Where(c => c.Id == 35).OrderBy(c => c.Name);

You will not connect to the database. You are only preparing the logical sequence of operations to translate into an SQL query.


AFTER THE QUESTION UPDATE

Now, your second example, with the ToList(), enumerate the results and connects to the database to get the data.

like image 61
Guilherme Avatar answered Sep 30 '22 11:09

Guilherme