Create Expression Tree For Selector

≡放荡痞女 提交于 2019-12-13 17:16:06

问题


Related To :

Create a Lambda Expression With 3 conditions

Convert Contains To Expression Tree

Convert List.Contains to Expression Tree

Please consider above questions.

I want to write a query for this:

using (MyEntities context = new MyEntities())
{
     var DbSet = context.CreateObjectSet<T>();
     var Max = DbSet.Where(exp).Select(selector).Max();
}

I don't know how to write a code for selector. What Select overload I should use? and How I can write that using Expression Tree?

Thanks


回答1:


What Select overload I should use?

The one with a single parameter in addition to the source:

public static IQueryable<TResult> Select<TSource, TResult>(
    this IQueryable<TSource> source,
    Expression<Func<TSource, TResult>> selector
)

How can I write that using Expression Tree?

Selector needs to take a TSource parameter, and produce the field of which you want to retrieve the Max. For example, let's say TSource is of type Employee, and you want to find the Max of its Salary property of type decimal. Then you would create an expression tree like this:

var p = Expression.Parameter(typeof(Employee));
var m = Expression.Property(p, "Salary");
var e = Expression.Lambda(m, p);
var selector = (Expression<Func<Employee,decimal>>)e;


来源:https://stackoverflow.com/questions/46645185/create-expression-tree-for-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!