Database Reference
In-Depth Information
context.Appointments.Add(app2);
context.Companies.Add(company);
context.SaveChanges();
}
using (var context = new Recipe3Context())
{
Console.WriteLine("Entities tracked in context for Doctors...");
// execute query using the AsNoTracking() method
context.Doctors.Include("Company").AsNoTracking().ToList();
Console.WriteLine("Number of entities loaded into context with AsNoTracking: {0}",
context.ChangeTracker.Entries().Count());
// execute query without the AsNoTracking() method
context.Doctors.Include("Company").ToList();
Console.WriteLine("Number of entities loaded into context without AsNoTracking: {0}",
context.ChangeTracker.Entries().Count());
}
Following is the output of the code in Listing 13-9:
Entities tracked in context for Doctors...
Number of entities loaded into context with AsNoTracking: 0
Number of entities loaded into context without AsNoTracking: 3
How It Works
When chaining the AsNoTracking method to your query, the objects resulting from that query are not tracked in
the context object. In our case, this includes the doctors and the companies the doctors work for because our query
explicitly included these.
By default, the results of your queries are tracked in the context object. This makes updating and deleting objects
effortless, but at the cost of some memory and CPU overhead. For applications that stream large numbers of objects,
such as browsing products at an ecommerce website, using the AsNoTracking option can result in less resource
overhead and better application performance.
As you are not caching the results of a query, each time you execute the query Entity Framework will need
to materialize the query result. Normally, with change tracking enabled, Entity Framework will not need to re-
materialize a query result if it is already cached in the context object.
When you include the AsNoTracking option (as we do in Listing 13-9), it only affects the current query for the
given entity and any related entities included in the query. It does affect subsequent queries that do not include the
AsNoTracking option, as demonstrated in Listing 13-9.
 
Search WWH ::




Custom Search