I was recently working on some migration of Ado.Net to EF 3.5 (not to EF4, due to some constraints). It was quite challenging for me to find out how to implement the Eager loading in EF3.5.
So i thought of sharing the code with anyone who needs it
public static class EFExtensions { public static TSource LoadAll<TSource>(this TSource source) where TSource : EntityObject { if (source != null) { Type type = source.GetType(); foreach (var property in type.GetProperties().Where(property => typeof(EntityReference).IsAssignableFrom(property.PropertyType))) { ((EntityReference)type.InvokeMember(property.Name, BindingFlags.GetProperty, null, source, null)).Load(); } foreach (var property in type.GetProperties().Where(property => typeof(EntityObject).IsAssignableFrom(property.PropertyType))) { var test = (EntityObject)type.InvokeMember(property.Name, BindingFlags.GetProperty, null, source, null); LazyLoad(test); } } return source; } public static List<TSource> LoadAll<TSource>(this IQueryable<TSource> source) { foreach (var entity in source) { if (!(entity is EntityObject)) continue; Type type = entity.GetType(); foreach (var property in type.GetProperties().Where(property => typeof(EntityReference).IsAssignableFrom(property.PropertyType))) { ((EntityReference)type.InvokeMember(property.Name, BindingFlags.GetProperty, null, entity, null)).Load(); } foreach (var property in type.GetProperties().Where(property => typeof(EntityObject).IsAssignableFrom(property.PropertyType))) { LazyLoad((EntityObject)type.InvokeMember(property.Name, BindingFlags.GetProperty, null, entity, null)); } } return source.ToList(); } }
Usage:
var employees = (from i in tm.Schema.company_employee where i.Company.ID == id select i).LoadAll();
or
var employee = from i in tm.Schema.Employees where i.ID == id select i; var oneEmployee = em.First().LoadAll().GetEmployeeObject();
The above seems to be working fine but feel free to test it or enhance it further. 🙂