Reputation: 322
I have two models
public class Contact
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public Branch Branch { get; set; }
}
public class Branch
{
public string BranchName { get; set; }
}
var parameter = Expression.Parameter(typeof(Contact), "c");
var secondParameter = Expression.Parameter(typeof(Branch), "b");
var properties = new[] { "FirstName", "BirthDate", "Branch.BranchName" };
var bindings = properties.Select(property =>
{
if (property.Contains("."))
{
var parts = property.Split('.');
var navigationProperty = Expression.Property(parameter, parts[0]);
var nestedProperty = Expression.Property(navigationProperty, parts[1]);
return Expression.Bind(
typeof(Branch).GetProperty(parts[1]),
nestedProperty
);
}
else
{
return Expression.Bind(
typeof(Contact).GetProperty(property),
Expression.Property(parameter, property)
);
}
}).ToArray();
var newExpression = Expression.New(typeof(Contact));
var memberInit = Expression.MemberInit(newExpression, bindings);
var lambda = Expression.Lambda<Func<Contact, object>>(memberInit, parameter);
my code is throwing an error on var memberInit = Expression.MemberInit(newExpression, bindings)
It thinks BranchName is part of Contact not Branch. When I debug, my binding for Branch.BranchName looks like this {BranchName = c.Branch.BranchName}
Is it not possible to query a virtual's property?
Upvotes: 0
Views: 22