views:

13

answers:

1

I'm iterating the tables of a context and then the properties of those tables to eager load all columns in a context. I received some help via another question, but I don't seem to be able to figure out how to iterate the column properties of the actual table.


Final working code:

public static void DisableLazyLoading(this DataContext context)
{
    DataLoadOptions options = new DataLoadOptions();

    var contextTables = context.GetType().GetProperties().Where(n => n.PropertyType.Name == "Table`1");
    foreach (var contextTable in contextTables)
    {
        var tableType = contextTable.GetValue(context, null).GetType().GetGenericArguments()[0];
        var tableProperties = tableType.GetProperties().Where(n => n.PropertyType.Name != "EntitySet`1");
        foreach (var tableProperty in tableProperties)
        {
            ParameterExpression paramExp = Expression.Parameter(tableType, "s");
            Expression expr = Expression.Property(paramExp, tableProperty.Name);
            options.LoadWith(Expression.Lambda(expr, paramExp));
        }
    }

    context.LoadOptions = options;
}
+1  A: 

You're only getting the ProperInfos. You need to get the values from the PropertyInfos:

var tablePropertInfos = context.GetType().GetProperties().Where(
    n => n.PropertyType.Name == "Table`1");

foreach (var tablePropertyInfo in tablePropertInfos)
{

    // Get the actual table
    var table = tablePropertyInfo.GetValue(context, null);

    // Do the same for the actual table properties

}

Once you have the PropertyInfo class, you need to get the value using the GetValue method.

GenericTypeTea
Ah, the `GetValue` makes so much sense now as to what it does. That is so close as it returns a `Table`1` type for each. Do you know how to cast it to the actual class/type that defines the table columns though? As it stands now I only get the properties of `Table`1` rather than the properties of an `Order` and `OrderItem` table, for example.
Jake Wharton
Updated question with current code. I'm only getting these two when debugging the inner `foreach`: http://msdn.microsoft.com/en-us/library/bb336216.aspx#propertyTableToggle
Jake Wharton
So you want the properties from the generic type of the `Table` result? I.e. in Table<Foo> you want `GetProperties` to return the properties of `Foo`?
GenericTypeTea
I got it thanks to http://stackoverflow.com/questions/293905/reflection-getting-the-generic-parameters-from-a-system-type-instance . Thanks for all your help!
Jake Wharton
No problem! Was just hunting for that answer myself :).
GenericTypeTea