Skip to content

Instantly share code, notes, and snippets.

@leandrosilva
Created May 19, 2021 23:05
Show Gist options
  • Save leandrosilva/83a4247ff036ab6c9b1ede3ce3f6dba6 to your computer and use it in GitHub Desktop.
Save leandrosilva/83a4247ff036ab6c9b1ede3ce3f6dba6 to your computer and use it in GitHub Desktop.
Extension method to lazy loading related fields of an entity
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace CodeZone.EntityFramework.Extensions
{
public static class EFLazyLoadingExtensions
{
public static void Load<TEntity, TRelated>(this TEntity entity, Expression<Func<TEntity, TRelated>> relatedSelector)
where TRelated : class
{
var lazyLoaderInfo = entity.GetType().GetField("_lazyLoader", BindingFlags.Instance | BindingFlags.NonPublic);
if (lazyLoaderInfo == null) throw new InvalidOperationException("Entity must declare a private field '_lazyLoader' of type 'Action<object, string>' injected by constructor.");
var lazyLoader = lazyLoaderInfo.GetValue(entity) as Action<object, string>;
var relatedProperty = (relatedSelector.Body as MemberExpression).Member;
lazyLoader.Invoke(entity, relatedProperty.Name);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment