What difference does .AsNoTracking() make?

dotnetnoob picture dotnetnoob · Aug 31, 2012 · Viewed 154.6k times · Source

I have a question regarding the .AsNoTracking() extension, as this is all quite new and quite confusing.

I'm using a per-request context for a website.

A lot of my entities don't change so don't need to be tracked, but I have the following scenario where I'm unsure of what's going to the database, or even whether it makes a difference in this case.

This example is what I'm currently doing:

context.Set<User>().AsNoTracking()
// Step 1) Get user
context.Set<User>()
// Step 2) Update user

This is the same as above but removing the .AsNoTracking() from Step 1:

context.Set<User>();
// Step 1) Get user
context.Set<User>()
// Step 2) Update user

The Steps 1 & 2 use the same context but occur at different times. What I can't work out is whether there is any difference. As Step 2 is an update I'm guessing both will hit the database twice anyway.

Can anyone tell me what the difference is?

Answer

Ladislav Mrnka picture Ladislav Mrnka · Aug 31, 2012

The difference is that in the first case the retrieved user is not tracked by the context so when you are going to save the user back to database you must attach it and set correctly state of the user so that EF knows that it should update existing user instead of inserting a new one. In the second case you don't need to do that if you load and save the user with the same context instance because the tracking mechanism handles that for you.