Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does using AsNoTracking() make a difference when only returning fields?

So I've read a lot about using AsNoTracking() when performing a query in EF, specifically if it returns entities, as to not keep around references to things if you will not be updating.

But I've also read that AsNoTracking may also speed up the queries themselves as EF does not have to map each item queried to an entity in the map.

The question is, if my Linq query simply returns values from the columns/rows but not an entity type, does using AsNoTracking() make a difference to speed up the query? And if not obviously I shouldn't use it because it just clutters the code?

example 1 (I would expect to use AsNoTracking():

var result = (from p in context.Pogs
              select p).AsNoTracking();

example 2 (My question... I'm thinking it doesn't make sense to use here, but I don't know the answer):

var result = (from p in context.Pogs
              select p.Name);  // assuming p.Name is a string or something

versus

var result = (from p in context.Pogs.AsNoTracking()
              select p.Name);
like image 681
Robert Noack Avatar asked Feb 11 '14 14:02

Robert Noack


1 Answers

No, it does not since the entities won't be loaded, as evidenced by examining context.Pogs.Local which won't contain the entities whose properties were retrieved through LINQ.

You can check the entities being tracked through DbContext.ChangeTracker. So if you retrieve the entries of the tracker for your Pogs DbSet through context.ChangeTracker.Entries<Pogs>() you'll see that for your first example there are entries tracking the corresponding entities, while for the second example there are none.

like image 88
jnovo Avatar answered Oct 30 '22 21:10

jnovo