I'd like to dynamically create a MemberAcess Expression to a deeper level then 1 (recursively):
public class Job
{
public string Name { get; set; }
public int Salary { get; set; }
}
public class Employee
{
public string Name { get; set; }
public Job Job { get; set; }
}
And I want to dynamically create a list of MemberAccesExpressions for each property in Employee and each property in Employee's complex members, the outcome should be something like this:
MemberAccesExpression[] {
{ e => e.Name },
{ e => e.Job.Name },
{ e => e.Job.Name }
}
This is a pseudo code of what I got:
List list = new List();
public Expression<Func<TModel, dynamic>> CreateME<TModel>(TModel model)
{
var type = typeof (TModel);
var properties = type.GetProperties();
foreach (var prop in properties)
{
// I want to ignore collections
if (typeof(ICollection).IsAssignableFrom(prop.PropertyType)) continue;
// Recall for complex property
if (prop.PropertyType.Namespace != "System")
{
// CreateME(model, ) // THIS IS WHEN I DON'T KNOW WHAT TO DO
continue;
}
var param = Expression.Parameter(type, "x");
var memberAccess = Expression.PropertyOrField(param, prop.Name);
list.Add(Expression.Lambda<Func<TModel, dynamic>>(memberAccess, param));
}
}
How do I make this a recursive method? I thought of adding an optional parameter named (TModel model, Expression> baseMemberAccess = null) and somehow concat the member expression to baseMemberAccess if it's not null.
P.S. is there's a better way to determine if a Type is not atomic type then this (prop.PropertyType.Namespace != "System") ? (not int,float,string,etc...)
Appreciate any help, Adam
An edit for trying to lay it more simply:
If I want to create an expression tree of a member access to Employee.Name this is what I do:
var param = Expression.Parameter(type, "x");
var memberAccess = Expression.PropertyOrField(param, memberName);
return Expression.Lambda<Func<TModel, TMember>>(memberAccess, param);
What is the equivalent to this for a member access to Employee.Job.Salary ?