Reputation: 3289
I have an EF5 Code First project that pulls from a mostly read-only database, so I'm using .AsNoTracking()
with the vast majority of my queries to improve performance.
I'm curious, though: I have a number of navigation properties, and at times it would be useful to know if they've already been loaded, either following an .Include()
on the source query, or due to the property being accessed (if configured for lazy loading).
Normally I could do:
context.Entry(myEntity).Reference(e => e.MyNavigationProperty).IsLoaded;
but naturally that won't work with untracked entities, since, well, they're untracked. I have a feeling the answer is "no," but is there a way to determine if a navigation property has been loaded on an untracked entity (without resorting to anything messy like reflection on the dynamic proxy)?
Thanks!
Upvotes: 4
Views: 941
Reputation: 1377
The solution below is not going to work with entities loaded from db by accessing not-tracked entity. Although subsequent reference to that navigation property do not create db hit, the navigation property is not tracked by Entity Framework. I'm leaving this as an example of how not to do it ;)
How about using Local? So let say you have
public class MyEntity
{
public int MyEntityId { get; set;}
public int MyNavigationPropertyID { get; set;}
public MNP MyNavigationProperty { get; set; }
}
public class MNP
{
public int MNPID { get; set;}
}
You can do that:
context.MyNavigationProperties.Local.Where(e => e.MNPID == MyNavigationProperty);
Local stores entities that are currently being tracked and not marked as deleted. I haven't tested that but it should work.
Upvotes: 1