This question is locked. New answers and comments are not allowed.
Sorry, this will be a bit complex but I found no easy way to reproduce.
Using the Northwind database and OA version 2015.1.225.1
// Basic visitor to replace the lambda parameter
class
ParameterTranslator : ExpressionVisitor
{
public
ParameterExpression OldParameter {
get
;
set
; }
public
ParameterExpression NewParameter {
get
;
set
; }
protected
override
Expression VisitParameter(ParameterExpression node)
{
return
node ==
this
.OldParameter
? NewParameter
:
base
.VisitParameter(node);
}
}
static
void
Main(
string
[] args)
{
using
( var db =
new
EntitiesModel1() )
{
Expression<Func<Employee,
bool
>> pred1 = r => r.FirstName ==
"Andrew"
;
var emps = db.Employees.Where(pred1);
Expression<Func<Employee,
bool
>> pred2 = r => emps.Any(r2 => r2.EmployeeID == r.ReportsTo);
// Combine the predicates by replacing pred2's parameter by pred1's and merge the bodies
var tr =
new
ParameterTranslator()
{
OldParameter = pred2.Parameters[0],
NewParameter = pred1.Parameters[0],
};
var body = Expression.OrElse(pred1.Body, tr.Visit(pred2.Body));
var pred = Expression.Lambda<Func<Employee,
bool
>>(body, pred1.Parameters[0]);
var q = db.Employees.Where(pred);
var str = q.ToString();
}
}
SELECT
*
FROM
[Employees] a
WHERE
a.[FirstName] =
'Andrew'
OR
EXISTS
(
SELECT
b.[EmployeeID]
FROM
[Employees] b
WHERE
b.[FirstName] =
'Andrew'
AND
b.[EmployeeID] = b.[ReportsTo]
)
The problem is with the last condition, it references the wrong table. It should be
AND
b.[EmployeeID] = a.[ReportsTo]
Is there any way (apart from cloning pred1's body on every use) to work around this?