Reputation: 926
Question
Is there any way to make it so that an entity returned from a DbContext query returns null (or some other specific value) when you try to access a navigation property that you did not specificly .Include()? For example:
var parents = dbContext.People.Where(p => p.Children.Any()).Include("Children").ToList();
//Assert all parents have children...
Assert.IsTrue(parents[0].Children.Any());
And...
var parents = dbContext.People.Where(p => p.Children.Any()).ToList();
//Assert all children collections are null... NOT LAZY LOADED
Assert.IsTrue(parents[0].Children == null);
To be clear, I do not want the property to be Eager-Loaded. I don't want it to be loaded at all. I've tried Detaching the entity from the context, but this doesn't help.
Background
The reason I am trying to do this is because i need to access the entity object on a diffrent thread than the one the DbContext was created on. Because of this, I do NOT want the navigation property to be set to some defered excution linq statement. The problem is that since I cannot access DbContext to check if a navigation property is loaded or not (due to it not being thread safe) I have no way of knowing if I need to create a new DbContext on the current thread to retrieve the missing data. This is the same problem that I was trying to solve with How to tell if a Navigation Property is loaded without DbContext
Update
Setting the DbContext's Configuration.LazyLoadingEnabled property to false prevents the linq from getting auto-wired up, but for navigation properties that are collections this results in a empty collection rather than null.
To solve the collection based problem, I Modified my T4 template to generate an empty default constructor rather than one that set each ICollection equal to an empty HashSet.
Upvotes: 1
Views: 1750
Reputation: 5489
You can enable / disable lazy-loading by setting the Configuration.LazyLoadingEnabled
property of your DbContext
context.Configuration.LazyLoadingEnabled = false;
var parents = dbContext.People.Where(p => p.Children.Any()).ToList();
context.Configuration.LazyLoadingEnabled = true;
Upvotes: 2