When are queries executed on DbContext

Viewed 1165

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?

1 Answers
Related