Question in short:
Is there a way to make EF throw an exception if the code accesses a navigation property and the data being requested is not loaded in memory and lazy loading is disabled?
A bit longer:
I'm using Entity Framework 4 (model first) and have disabled lazy loading. Before, if I run something like the following, the code would run fine but be slow since every call to customer.Orders resulted in a new SQL query being executed:
int totalValue = 0;
foreach(var customer in efContext.Customers)
foreach (var order in customer.Orders)
totalValue += order.Value;
I wanted to disable lazy loading completely to prevent such code from be introduced in the code base I'm working on. What I wanted to happen is that when the code executes customer.Orders, an exception should be thrown stating something along the lines of "Entity not loaded. Lazy loading is off.". But instead, the list of orders is simply empty because the orders has not been loaded.
I feel that this behavior may also be problematic, just in a different way than lazy loading. A developer who was tasked with checking that every customer has a contact could write something like the following:
if (customer.Contact != null)
throw new BlablablaException("Customer lacks contact");
But with lazy loading disabled, customer.Contact would always be null, and the developer might think that his code works properly. Sure, he should do his job properly and test both scenarios (contact existing, contact not existing) but it would be much more clear if an exception was thrown.
In my opinion, it seems strange that Entity Framework does not throw an exception if I try to access data which is not available and instead just returns an empty list.
Is there an explanation to this behavior? And is there a way to make EF throw exception when a navigation property is called and the data is not avaialble?