Patrick Desjardins Blog
Patrick Desjardins picture from a conference

AsNoTracking() to force your data context to get everything from the database

Posted on: 2013-03-28

You can specify Entity Framework to get everything back from the database instead of using what has been already loaded from the database.

A use case would be that you attach an entity from the web form and you save everything. You may return the view from the entity loaded but this one won't get the full object if it has been attached previously.

public Workout Get(int id) { 
  return DatabaseContext 
  .SetOwnable<Workout>() 
  .Include(x => x.Sessions) 
  .Include("Sessions.WorkoutSessionExercises") 
  .Include("Sessions.WorkoutSessionExercises.Exercise") 
  .AsNoTracking() 
  .Single(c => c.Id == id); 
} 

With the addition of AsNoTracking, the information won't be get from the local storage of the database context but from the database.