Reputation: 5524
I have implementation like this:
var query = this.DbContext.Set<T>();
if (includeProperties != null && includeProperties.Any())
{
foreach (var includeProperty in includeProperties)
{
if (!String.IsNullOrEmpty(includeProperty))
{
query = query.Include(includeProperty);
}
}
}
return await query.Where<T>(predicate).ToListAsync();
I'd like to make this query AsNoTracking()
and I'm interested if its important where to call AsNoTracking()
?
Does it make any difference if I put it here:
var query = this.DbContext.Set<T>().AsNoTracking();
or here:
return await query.Where<T>(predicate).AsNoTracking().ToListAsync();
Will both perform query .AsNoTracking()
same way or not?
Also I'm interested if .Include()
is also affected by any of these .AsNoTracking()
or do I have to put additional .AsNoTracking()
like this:
query = query.Include(includeProperty).AsNoTracking();
I'm having trouble with .Include()
because I get infinite recursive navigation properties and when using Automapper
I get stackoverflow
, so I'm not quite sure if I'm using AsNoTracking()
correctly (or AsNoTracking()
doesn't affect infinite nesting of properties, although I read that somewhere, but only tracks changes in Context
for further CUD operations?)
I also have these in my Context subclass:
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
Though my main problem is inifinite navigation property references, I'd really appreciate if someone could also explain correct usage of AsNoTracking()
from beginning of question (although, for example, it doesn't have anything to do with the problem).
Thank you.
Upvotes: 3
Views: 1679
Reputation: 101553
No it's not important where to call AsNoTracking()
. Basically all it does is sets ObjectQuery.MergeOption (and some other properties) on internal ObjectQuery
, so it doesn't matter where to do that until actual query execution.
Yes, all Include
ed entities will also not be tracked by a context.
No, LazyLoadingEnabled = false
, ProxyCreationEnabled = false
and AsNoTracking()
will not solve all your infinite recursion problems, especially if you are using includes. Look for how to map such recursive entities with automapper correctly, doing anything on EF side will not help.
Upvotes: 4