用于引用将Expression返回给另一个方法的方法的语法?

Sha*_*ica 6 .net c# linq expression expression-trees

我找到了一段以下形式的代码:

public static Expression<Func<Invoice, CustomerContact>> GetCustomerContact()
{
   return i => new CustomerContact {
                 FirstName = i.Customer.FirstName,
                 LastName = i.Customer.LastName,
                 Email = i.Customer.Email,
                 TelMobile = i.Customer.TelMobile,
               };
}
Run Code Online (Sandbox Code Playgroud)

在代码的其他部分,我想获得相同的轻量级CustomerContact对象,但不是来自Invoice,而是来自Customer本身.因此,显而易见的事情是:

public static Expression<Func<Customer, CustomerContact>> GetCustomerContact()
{
   return c => new CustomerContact {
                 FirstName = c.FirstName,
                 LastName = c.LastName,
                 Email = c.Email,
                 TelMobile = c.TelMobile,
               };
}
Run Code Online (Sandbox Code Playgroud)

然后将Expressiontake Invoice作为输入更改为引用此方法,即如下所示:

public static Expression<Func<Invoice, CustomerContact>> GetCustomerContact()
{
   return i => GetCustomerContact(i.Customer); // doesn't compile
}
Run Code Online (Sandbox Code Playgroud)

这个的正确语法是什么?

Ani*_*Ani 3

您可以使用Expression.Invoke

var paramExpr = Expression.Parameter(typeof(Invoice), "i");
var propertyEx = Expression.Property(paramExpr, "Customer");

var body = Expression.Invoke(GetCustomerContactFromCustomer(), propertyEx);

return Expression.Lambda<Func<Invoice, CustomerContact>>(body, paramExpr);
Run Code Online (Sandbox Code Playgroud)

请注意,某些 LINQ 提供程序在此类调用表达式方面存在问题。

解决这个问题的最简单方法(并为您提供更方便的语法)是使用LINQKit

var expr = GetCustomerContactFromCustomer();   
Expression<Func<Invoice, CustomerContact>> result = i => expr.Invoke(i.Customer);    
return result.Expand();
Run Code Online (Sandbox Code Playgroud)