Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hbulens/60a063a8053cd48ae5913207ab06dfef to your computer and use it in GitHub Desktop.
Save hbulens/60a063a8053cd48ae5913207ab06dfef to your computer and use it in GitHub Desktop.
internal static IQueryable<TEntity> Include<TEntity>(this IQueryable<TEntity> query, DbContext context, params string[] includes) where TEntity : class
{
// Do a safety check first
if (includes == null)
return query;
List<string> includeList = new List<string>();
if (includes.Any())
return includes
.Where(x => !string.IsNullOrEmpty(x) && !includeList.Contains(x))
.Aggregate(query, (current, include) => current.Include(include));
IEnumerable<INavigation> navigationProperties = context.Model.FindEntityType(typeof(TEntity)).GetNavigations();
if (navigationProperties == null)
return query;
foreach (INavigation navigationProperty in navigationProperties)
{
if (includeList.Contains(navigationProperty.Name))
continue;
includeList.Add(navigationProperty.Name);
query = query.Include(navigationProperty.Name);
}
return query;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment