从导航属性选择器字符串 C# 创建成员表达式
本文关键字:创建 成员 表达式 字符串 导航 属性 选择器 | 更新日期: 2023-09-27 18:32:26
我们有以下实体:
public class Employee
{
public int Serial { get; set; }
public string FullName { get; set; }
public Section Section { get; set; }
}
public class Section
{
public int Serial { get; set; }
public string SectionName { get; set; }
public SupperSection SupperSection { get; set; }
public ICollection<Employee> Sections { get; set; }
}
我们希望从以下字符串创建一个MemberExpression
:
Employee.Section.SectionName
我们这样做如下:
// selectorString = Section.SectionName
// we wanna create entity => entity.Section.SectionName
ParameterExpression parameterExpression = Expression.Parameter(entityType, "entity");
MemberExpression result = Expression.Property(parameterExpression, selectorString); // Exception
但它抛出以下异常:
类型为"System.ArgumentException"的未处理异常发生在系统核心.dll
其他信息:未为类型"DtoContainer.Employee"定义属性"System.String SectionName"
我们该怎么做?
您需要创建对象实例并构建如下所示的表达式树:
Employee employee = new Employee()
{
Section = new Section() { SectionName = "test" }
};
MemberExpression sectionMember = Expression.Property(ConstantExpression.Constant(employee), "Section");
MemberExpression sectionNameMember = Expression.Property(sectionMember, "SectionName");
var selectorString = "Employee.Section.SectionName";
var properties = selectorString.Split(".");
var property = Expression.Property(parameter, properties[0]);
//You can add like this
property = properties.Skip(1).Aggregate(property, (current, propertyName) => Expression.Property(current, propertyName));
//or you use a shorter version by passing as a method group
property = properties.Skip(1).Aggregate(property, Expression.Property);
var expression = Expression.Lambda(typeof(Func<,>).MakeGenericType(typeof(TEntity), property.Type), property, parameter);