Should I turn off lazy loading in Entity Framework?
So I've been getting this feeling that I should turn off lazy loading, for two reasons:
- queries become non-atomic, so could result in concurrency errors.
- me or another programmer could end up causing a huge performance impediment.
Of course, both of these problems can be avoided as long as we're careful, but it seems a bit of an unnecessary risk in projects where performance is somewhat important.
As a side note, I found it weird that 1-* relationship properties become null
rather than throwing an exception when you access them with lazy loading off. I want to go back and do everything in single queries, but I'm worried that I might overlook a bug where I'm interpreting a not-yet-loaded 0-* relationship as being null开发者_如何学编程
.
Thoughts?
Turn off lazy loading if your worried about performance, if you're not, don't.
Personally, we turn off lazy loading, and explicitly allow the inclusion of navigational properties via the interface contract for our repositories, e.g:
ICollection<Person> FindSingle(int personId, string[] includeAssociations);
So we then eager-load the navigational properties ONLY if the calling code specifically asks for it. It's like saying to the code: "Hey, if you want extra information about this T, then ASK for it, otherwise you ain't gettin it!".
As for the 1-*, of course the properties are null. Navigational properties are generally implemented as ICollection<T>
on the objects, so if there is nothing there, a collection isn't instantiated.
You could counteract this effect by creating an empty collection, rather than a null one when you execute your queries. However, i prefer a null collection to an instantiated one with 0 items.
精彩评论