Wednesday 7 January 2015

ASP.NET Tips #12 - Turn off change tracking in Entity Framework (EF)

If you have to query a database for some read-only data in Entity Framework, make sure that Change Tracking is turned off, so you're not tracking individual objects or object graphs whose state won't change. Use some code along these lines to do it:

Context.MyCollection.AsNoTracking().where(x => x.Id);

For Example:

using (var context = new OrdersContext())
{
   // Query for all orders without tracking them
   var allOrders = context.Orders.AsNoTracking().ToList();

   // Query for some orders without tracking them
   var someOrders = context.Orders
      .Where(b => b.Name.Contains("iPad"))
      .AsNoTracking()
      .ToList();
}

AsNoTracking() is an extension method defined on IQueryable, so you'll need to import the System.Data.Entity namespace. For more details, to understand the performance gains of AsNoTracking(), have a look at:

http://msdn.microsoft.com/en-us/library/cc853327.aspx
http://blog.staticvoid.co.nz/2012/4/2/entity_framework_and_ asnotracking

1 comment :

  1. Does "AsNoTracking()" works in ASP.NET 4.0?
    I have tried in ASP.NET 4.0, I could not find System.Entity.Data but I found System.Data.Entity!

    ReplyDelete