I don't know if it is expected to be this way but I thought it is strange since changes the query results.
When I execute the query below I get my entity with only 2 "Mensagens" entity because i'm filtering only the actives so it's right, I have 2 active entities on my database and 1 inactive.
return await context.Lancamentos
.Include(x => x.UsuarioCriacao)
.Include(x => x.Mensagens.Where(m => m.Ativo))
.ThenInclude(m => m.MensagemMedias)
.ThenInclude(m => m.MediaWhatsapp)
.ThenInclude(m => m.TipoMediaWhatsapp)
.Include(x => x.Mensagens.Where(m => m.Ativo))
.ThenInclude(x => x.TemplateMensagem)
.ThenInclude(t => t.Medias)
.ThenInclude(m => m.MediaWhatsapp)
.ThenInclude(m => m.TipoMediaWhatsapp)
.AsNoTracking()
.FirstOrDefaultAsync(l => l.Id == id && l.Ativo);
But if I execute the exact same command just removing the AsNoTracking() line it gives me the 3 records, both active and inactive.
But the inactive one EF doesn't fetch the ThenInclude below. It changes the behaviour.
With AsNoTracking it filters the data according to the filter I used on Include
Without AsNoTracking it bring me all the data but it filters if it will load or not the ThenInclude objects.
Does anyone know if this is a normal behaviour and why does it behaves like this?
This is sort of explained in Filtered include documentation:
Caution
In case of tracking queries, results of Filtered Include may be unexpected due to navigation fixup. All relevant entities that have been queried for previously and have been stored in the Change Tracker will be present in the results of Filtered Include query, even if they don't meet the requirements of the filter. Consider using
NoTrackingqueries or re-create the DbContext when using Filtered Include in those situations.
So most likely your context is not clean when doing tracking tests. And even if it is clean, in case it is used for executing other queries, the navigation fixup can load some non satisfying filter entities later since it keeps track (has access) to all tracked entities.
In general you cannot rely on content of navigation property of a tracked entity since it may be updated at any time during the lifetime of the context until the context is disposed or entity detached from change tracker. If you need full control, the either use no tracking entity queries or DTO/ViewModel etc. projecting queries and select exactly what you want (no Include / ThenInclude, just plain LINQ).