❔ Expression<Func> using Reflection

Hello, I'm using LINQ to SQL as part of an old legacy Business Object Layer and trying to use the following code using reflection instead of hardcoding the types. Currently I have:
DataLoadOptions loadOptions = new DataLoadOptions();
loadOptions.LoadWith<WorkRequest>(m => m.WorkRequestItems);
dc.LoadOptions = loadOptions;
Table table = dc.GetTable<WorkRequest>();
DataLoadOptions loadOptions = new DataLoadOptions();
loadOptions.LoadWith<WorkRequest>(m => m.WorkRequestItems);
dc.LoadOptions = loadOptions;
Table table = dc.GetTable<WorkRequest>();
This loads WorkRequestItems with WorkRequest upon execution. However, the desired outcome is to turn WorkRequest into T So something like:
DataLoadOptions loadOptions = new DataLoadOptions();
loadOptions.LoadWith<T>( //targetChildObject );
dc.LoadOptions = loadOptions;
Table table = dc.GetTable<T>();
DataLoadOptions loadOptions = new DataLoadOptions();
loadOptions.LoadWith<T>( //targetChildObject );
dc.LoadOptions = loadOptions;
Table table = dc.GetTable<T>();
T gets passed in from the controller. loadOptions.LoadWith<T> expects Expression<Func<T, object>> expression as it's argument. Any help would be appreciated.
3 Replies
phaseshift
phaseshift2y ago
Expression.Lambda<Func<T, object>>(...) gets you most of the way there. That will create your 'expression'. You need to figure out the arguments I think the func input arg would be Expression.Parameter(typeof(T), "t") So youd need to build up the inner expression for the lambda
WibblyWobbly
WibblyWobblyOP2y ago
Yes this is where I got to:
ParameterExpression parameter = Expression.Parameter(type, "m");
Expression<Func<T, object>> lambdaExpression = Expression.Lambda<Func<T, object>>(
Expression.Property(parameter, "WorkRequestItems"), parameter);
ParameterExpression parameter = Expression.Parameter(type, "m");
Expression<Func<T, object>> lambdaExpression = Expression.Lambda<Func<T, object>>(
Expression.Property(parameter, "WorkRequestItems"), parameter);
It works in retrieving the data, the return format in the json isn't quite there yet but that might just be me. Thank you!
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server