I'm not much of a DB guy and I'm pretty new to EF. I am confused by the erratic behavior of lazy loading on FK relationships.
Let's say I have a table Parent and a table Children. Children has a non-unique FK into Parent. Now some code:
Parent GetParent(int parentId)
{
return Entities.Parents.Single(p => p.ParentId == parentId);
}
Child GetChildByName(int parentId, string name)
{
var parent = GetParent(parentId);
return parent.Children.Single(c => c.Name == name);
}
Now, sometimes the call to parent.Children.Single
will fail because the sequence Parent.Children
is empty. Not always, but sometimes, which makes this terribly frustrating. When it does fail I have verified via Intellitrace that no SQL call to fetch Children
has executed.
This relationship is already created correctly in the database and all input parameters are correct.
If I use Include("Children")
and eagerly load all Children it will of course work every time.
If I throw a Thread.Sleep(1000)
in after I get the Parent but before I filter for a Child, the Children will more often than not be loaded and the call succeeds.
So, as far as I can tell, this is a timing related issue. FK relationships are not being loaded on demand, but they are being loaded at seemingly arbitrary times. I don't understand this behavior and I assume that I must be missing something.
I really don't want to add Include("SomeFK")
everywhere as it makes my code more brittle and, really, why should I have to do that? If I have to sprinkle calls to Include
all over the place I am
A) Grabbing data I often don't need B) Writing code which I must edit whenever I add or remove relationships C) Not getting much (aside from trivial code generation) out of my ORM. I may as well be writing raw SQL calls at this point.
So yeah, I must be missing something, but I've looked and have not been able to find a comprehensive explanation of lazy loading using POCO types (database first!) for EF.