In my last post I described the different types of entity that EF supports. But which type of entity should you use?
I was going to write a post about when to use change-tracking proxies. But I then thought before doing that it would be useful to go over all the different types of classes that the Entity Framework supports, of which change-tracking proxies is one. So here they are, in chronological order of when they were implemented/introduced.
In the last three posts we looked at an implementation of extra-lazy Count for EF 4.1 and how to reduce the Reflection cost of this implementation. However, when looking at LazyCountCollection it is fairly apparent that the same pattern can be used for more than just extra-lazy Count. In this we’ll look at a more general implementation of ICollection<T> that contains an underlying IQueryable<T> that can be used for more than just extra-lazy Count.
In my previous two posts I showed how to implement an extra-lazy Count property using EF 4.1. However, the code required that a lot of .NET Reflection happen for every entity returned by a query. The real-world performance impact of this can vary greatly, but for an application that queries for a lot of entities it could be significant.
Before going any further I should say that I haven’t profiled any of this, but we frequently write code that does this kind of work inside the Entity Framework and experience has shown that it often becomes a performance bottleneck. That’s why we always look for ways to make it faster and this usually comes down to doing the work once and then caching the results for every subsequent use. That’s what I am going to show here.
Lazy loading of collections is the process whereby a collection of entities is automatically loaded from the database the first time that the collection property referring to the entities is accessed. Support for lazy loading was added to Entity Framework 4.0 and is described here for EF 4.1. EF Lazy loading works with (almost) any implementation of ICollection<T> and does not mess with that implementation.
Lazy loading is useful in that it doesn’t require all entities that an application might use to be eagerly loaded up-front and also doesn’t require special code to be written to explicitly load related entities when they are needed—you just access the collection and it is automatically loaded if needed.
For some people lazy loading doesn’t go far enough. In particular, it is not uncommon to want to know how many related entities exist without actually loading all those entities.