如何创建表达式<func <t,t =“”>&gt;给T的属性名称映射?

时间:2017-12-01 05:34:09

标签: entity-framework linq expression

这是所需功能的样子:

 public static Expression<Func<T, T>> GetExpression<T>(string propertyNames) where T : class
 {
       var properties = propertyNames.Split(
            new char[] { ',' }, 
            StringSplitOptions.RemoveEmptyEntries
        ).ToList();

       //need help here
 }

目前我这样做:

_context.Questions.Select(q => 
                new Question() {
                    QuestionId = q.QuestionId,
                    QuestionEnglish = q.QuestionEnglish
                }
).ToList();

我想用以下内容替换它:

_context.Questions.Select(GetExpression<Question>("QuestionId, QuestionInEnglish")).ToList();

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

你可以这样做;

    public static Func<T, T> GetExpression<T>(string propertyNames)
    {
        var xParameter = Expression.Parameter(typeof(T), "parameter");

        var xNew = Expression.New(typeof(T));

        var selectFields = propertyNames.Split(',').Select(parameter => parameter.Trim())
            .Select(parameter => {

                    var prop = typeof(T).GetProperty(parameter);

                    if (prop == null) // The field doesn't exist
                    {
                        return null;
                    }
                    var xOriginal = Expression.Property(xParameter, prop);

                    return Expression.Bind(prop, xOriginal);
                }
            ).Where(x => x != null);

        var lambda = Expression.Lambda<Func<T, T>>(Expression.MemberInit(xNew, selectFields), xParameter);

        return lambda.Compile();
    }

用法;

    var list = new List<Question>{new Question{QuestionEnglish = "QuestionName",QuestionId = 1}};
    var result = list.Select(GetExpression<Question>("QuestionId, QuestionEnglish"));