Keith Walton
Keith Walton

Reputation: 5364

Does Entity Framework automatically load all of my data (not a reference and lazy load is off)?

I have a database first Entity Framework project. For every entity that I add, a collection is added to the DbContext for the entity. I explicity set LazyLoadingEnabled = false in the DbContext constructor. If I break into the following code and check the count of CustomerDepartments, I get the total count of the table. If I'm just adding a new record, I expect the count to be 0 before I add, and 1 after. I'm using this in a stateless environment, so loading the whole table just to add a record seems absurd. What am I doing wrong?

using (Model.SupportEntities support = new Model.SupportEntities(_state.Credentials, _handler.ReadWriteConnectionString)) 
{
    Model.CustomerDepartment department = Json.JsonConvert.DeserializeObject<Model.CustomerDepartment>(_insertObject);
    support.CustomerDepartments.Add(department);
    support.SaveChanges();
    _state.ReturnNewIdAsJson(department.CustomerDepartmentID);
}

Upvotes: 0

Views: 184

Answers (1)

Aron
Aron

Reputation: 15772

It seems you have misinterpreted how DbContext and DbSet works.

It maybe best if you get hold of a tool for logging EntityFramework SQL calls try Clutch.Diagnostics.EntityFramework.

When you call IEnumerable<T>.Count() on DbSet<T>, Entity Framework runs the following query

SELECT COUNT(*) FROM TableName;

But it does not load the whole table.

The ACTUAL call you want for the behavior you wanted was either

support.CustomerDepartments.Local.Count;

OR

support.ChangeTracker.Entries<T>().Count()

These will NOT hit the database.

You have to remember that DbSet is an abstraction for the Database table, so calling Count() on it should tell you how many rows there are in the table.

BTW. FYI. The convention is call name your DbContext to be SupportContext. Model named classes or namespace suggests they are your POCOs.

Upvotes: 1

Related Questions