When requests are executed in a DbContext

I am trying to understand the effect of performance on the use of a single DbContext vs multiple class when using the EF6 framework.

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

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

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

Now let's say that I have a service that uses the specified DbContext as follows:

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

At what point did DbContext go to the database and get all the 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 the former, if I had a DbContext that contains 100 tables, will all 100 tables be set when creating the DbContext?

+4
1

. . - .

, :

dbContext.Cars.ToList();

foreach (Car c in dbContext.Cars)

.

, -, , .., .

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

. SQL-.


, , ToList(), .

+6

Source: https://habr.com/ru/post/1678197/


All Articles