Lazy Loading and the Entity Framework. How long I can go on like this?
In more recent times I have spent a fair slice of time looking at how to get lazy loading working in the Entity Framework (without using the codeplex solution). Oddly, the driver for this was to get Fetching Strategies implemented for the Entity Framework and not the other way around and I have devoted a quite a few posts recently to that.
If you have followed the story until now, then you will know that I developed a method of transparently lazy loading by using some AOP style trickery and weaving code into the Entities themselves. I did say that I wasn’t going to post on this but it will become apparent why I chose to liberally change my mind about that as we move through this post. Currently the way to have your entity ‘opt’ into lazy loading (with my code), is to decorate it with an attribute in the partial class representation of the Entity itself.
[LazyLoad("Customer", AttributeTargetMembers = @"regex:(Customer$)")] [LazyLoad("Order_Details", AttributeTargetMembers = @"regex:(Order_Details$)")] public partial class Order : IFetchable { private IFetchingStrategy _strategy; public IFetchingStrategy FetchingStrategy { get { return _strategy; } set { _strategy = value; } } }
While we are waiting…..
Step by Step
- Download the code
- Copy the LazyLoadAttribute.cs file into your project with an entity model
- Reference the PostSharp.Laos, PostSharp.Public libraries.
- Reference the Org.TechAvalanche.Orm.Repository library
- Decorate the Partial class representation of your Entity with the LazyLoad attribute (copied in the second step) and your done. Write your fetching strategies, Repositories and Specifications and away you go.
I will soon follow with an Item Template for VS.Net that creates the attribute file and makes the references for you automatically.


