I'm New to EF and .Net, and nothing I've read or searched-for has prepared me for what I'm seeing - any help is appreciated!
(A#1: It's not. It's just the debugger trying to help by loading data automagically.)
(A#2: Ignore the DbContext object and look at the DbSet & Query objects.)
Reason for asking:
Think I've ruled out:
Haven't looked at:
Have several projects in the .sln (VS2015 community) playing with CQRS pattern (EF6, MVC5, SimpleInjector)
In Data.Read project, while set to startup, the Main class has the following "Play-Code" with a breakpoint as:
using ( MyDbContext dbcontext = new MyDbContext() )
{
//BREAKPOINT: Why is dbcontext full of data simply upon instantiation!?
//(while Debugging, Every row, from every table, is populated in Locals/ResultsView of dbcontext)
//No explicit Linq queries have been run
Why is my DbContext full of data simply upon instantiation!?
DbContext
does not load the data. Your debugger does. The debugger allows you to view the data, and when you view it the DbContext
will query the database. But it won't do it otherwise. This can easily be tested with SQL Server Profiler. Run it up and you will see that your DbContext
doesn't query your database until you use your debugger to view it.
How do I get it to instantiate as an empty "repo/container" object for loading data via my explicit queries?
The most simple way would be to just get the table.
Say that your DbContext
looks like this:
public class MyDbContext : DbContext
{
public DbSet<Customer> Customers {get; set;}
}
Then you can get your container like so:
using(var context = new MyDbContext())
{
// Get the table. This can serve as your repository.
DbSet<Customer> table = context.Customers;
// If you're using generics you can do like this as well.
DbSet<Customer> otherTable = context.Set<Customer>();
// Specify your explicit query.
IQueryable<Customer> query = table.Where(x => x.Name == 'Jenny');
// Note that EF still haven't executed a query.
// By calling methods like ToList() or FirstOrDefault() it will run the query.
IList<Customer> result = query.ToList();
}