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?
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.
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.
Developers can use the return keyword with or without a value. If a value is specified, it will be returned to the caller.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With