Funky Behavior NoTracking Query Entities

I’ve been using a lot of NoTracking queries to grab lists of data that I don’t need change tracked. It enhances performance and cuts down on resources. There are some nuances about these entities, however.

One of the interesting behaviors of EF4’s Lazy Loading is that even if you have entities that you have queried with NoTracking on, they will still lazy load related entities.

Unless you’ve read this somewhere (it’s on the ADO.NET team’s blog post which introduces lazy loading) or experienced it yourself (that’s me, since I had forgotten about that point in the blog post) you may not expect, or plan ahead, for this behavior.

You’d think that because the entity is not attached  to the context, it would not be able to pull this off. But it does. The related entity or collection will get automatically retrieved and the results are also detached and deep inside of the EntityObject sealed properties, there’s a flag that indicates they are NoTracking entities.

Another surprise is in store when you use NoTracking entities…again it’s only a surprise if you don’t happen to be aware of this behavior and it’s not what you might expect.

Normally when you join a detached entity to an attached entity, EF’s relationship span will kick in and automatically pull that detached entity into the context to be managed. However, this won’t happen with NoTracking entities and you’ll receive a very explicit exception message that explains this. You need to attach the “NoTracking” entity to the context first and then you can attach it to the other entity.

  Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!  

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.