gpt4 book ai didi

c# - 从导航属性选择器字符串创建 MemberExpression,C#?

转载 作者:行者123 更新时间:2023-11-30 22:02:02 28 4
gpt4 key购买 nike

我们有以下实体:

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

但它抛出以下异常:

An unhandled exception of type 'System.ArgumentException' occurred inSystem.Core.dll

Additional information: Property 'System.String SectionName' is not defined for type 'DtoContainer.Employee'

我们该怎么做?

最佳答案

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

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

关于c# - 从导航属性选择器字符串创建 MemberExpression,C#?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27210464/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com