Skip to content

Instantly share code, notes, and snippets.

@JakeWharton
Created August 3, 2010 15:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JakeWharton/506573 to your computer and use it in GitHub Desktop.
Save JakeWharton/506573 to your computer and use it in GitHub Desktop.
Disable any lazy loading of table properties by magical reflection voodoo
namespace JakeWharton.Utilities
{
public static class DataContextExtensions
{
/// <summary>
/// Disable any lazy loading of table properties by magical reflection voodoo.
///
/// See: http://stackoverflow.com/questions/3388276/disable-all-lazy-loading-or-force-eager-loading-for-a-linq-context
/// And: http://stackoverflow.com/questions/3396426/iterating-tables-in-a-context-and-the-properties-of-those-tables
/// And: http://stackoverflow.com/questions/3397843/how-to-determine-lazy-loaded-properties-at-runtime-on-a-linq-table
/// </summary>
/// <param name="context">Data context</param>
public static void DisableLazyLoading(this DataContext context)
{
DataLoadOptions options = new DataLoadOptions();
//Iterate all Tables in the DataContext
var contextProperties = context.GetType().GetProperties().Where(n => n.PropertyType.Name == "Table`1");
foreach (var contextProperty in contextProperties)
{
var tableType = contextProperty.GetValue(context, null).GetType().GetGenericArguments()[0];
//Iterate all Columns in the Table
var tableProperties = tableType.GetProperties().Where(n => n.PropertyType.Name != "EntitySet`1");
foreach (var tableProperty in tableProperties)
{
//Ensure we have at least 1 attribute (should denote that it is a mapping-defined property)
var columnAttributes = tableProperty.GetCustomAttributes(typeof(ColumnAttribute), true);
if (columnAttributes.Length > 0)
{
//Get the field which the Storage attribute points too and ensure it is lazy loaded
var field = tableProperty.DeclaringType.GetField((columnAttributes[0] as ColumnAttribute).Storage, BindingFlags.Instance | BindingFlags.NonPublic);
if ((field != null) && field.FieldType.IsGenericType && (field.FieldType.GetGenericTypeDefinition() == typeof(Link<>)))
{
//Add column to the LoadOptions as eager loaded
ParameterExpression paramExp = Expression.Parameter(tableType, "s");
Expression expr = Expression.Property(paramExp, tableProperty.Name);
options.LoadWith(Expression.Lambda(expr, paramExp));
}
}
}
}
context.LoadOptions = options;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment