Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax to refer a method returning an Expression to another method?

I found a piece of code of the following form:

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,
               };
}

In other parts of the code, I want to get the same lightweight CustomerContact object, only not from the Invoice, but from the Customer itself. So the obvious thing to do would be to have:

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

and then change the Expression taking Invoice as input to refer to this method, i.e. something like this:

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

What's the correct syntax for this?

like image 413
Shaul Behr Avatar asked Jun 02 '13 08:06

Shaul Behr


People also ask

What is the syntax used to return a value within a method?

You declare a method's return type in its method declaration. Within the body of the method, you use the return statement to return the value.

How do you return a value from one method to another in Java?

Instead, we can call the method from the argument of another method. // pass method2 as argument to method1 public void method1(method2()); Here, the returned value from method2() is assigned as an argument to method1() . If we need to pass the actual method as an argument, we use the lambda expression.

What is the keyword used to used to return value back to the calling method?

Developers can use the return keyword with or without a value. If a value is specified, it will be returned to the caller.


1 Answers

You can use 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);

Do note that some LINQ providers have problems with such invocation-expressions.

The easiest way to work around this (and to give you more convenient syntax) is to use LINQKit:

var expr = GetCustomerContactFromCustomer();   
Expression<Func<Invoice, CustomerContact>> result = i => expr.Invoke(i.Customer);    
return result.Expand();
like image 76
Ani Avatar answered Oct 14 '22 05:10

Ani