Created
May 19, 2021 23:05
-
-
Save leandrosilva/83a4247ff036ab6c9b1ede3ce3f6dba6 to your computer and use it in GitHub Desktop.
Extension method to lazy loading related fields of an entity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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