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?
At what point in time did the DbContext go to the database and retrieved all cars that are stored in the database?
In that code? Never. It will not work, theCars
property on the DBContext should be of typeDbSet<Car>
DbSet<T>
, it'll only fetch data from the database when you explicitly tell it to by calling something likeToList()
.Cars
by itself doesn't do anything - it's a container for entities but it's not holding all the data unless you make it so. If you useIQueryable
with Linq, data will only be pulled when you evaluate the enumerator or when you execute a SQL statement against the underlying connection through the context.