【问题标题】:Create MemberExpression from a navigation property selector string, C#?从导航属性选择器字符串创建 MemberExpression,C#?
【发布时间】:2017-09-18 01:22:51
【问题描述】:

我们有以下实体:

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”类型的未处理异常发生在 System.Core.dll

附加信息:没有为类型“DtoContainer.Employee”定义属性“System.String SectionName”

我们该怎么做?

【问题讨论】:

    标签: c# linq expression


    【解决方案1】:

    您需要像这样创建对象实例并构建表达式树:

    Employee employee = new Employee()
    {
        Section = new Section() { SectionName = "test" }
    };
    MemberExpression sectionMember = Expression.Property(ConstantExpression.Constant(employee), "Section");
    MemberExpression sectionNameMember = Expression.Property(sectionMember, "SectionName");
    

    【讨论】:

      【解决方案2】:
      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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-09
        相关资源
        最近更新 更多