1

I have following entity model:

public class SortableEntity {
  public long Id { get; set; }
  public int IntProperty { get; set; } 
}

And following failing test case:

[Fact]
public async Task TestExpression()
{
    Expression<Func<SortableEntity, long>> expression1 = e => e.Id;
    Expression<Func<SortableEntity, int>> expression2 = e => e.IntProperty;

    var predicateLambda = Expression.Lambda<Func<SortableEntity, bool>>(
        Expression.And(
            Expression.Equal(
                expression1.Body,
                Expression.Constant(123L)
            ),
            Expression.GreaterThan(
                expression2.Body,
                Expression.Constant(456)
            )
        ),
        expression1.Parameters[0] // not sure what should go here
    );

    await _db.SortableEntities.Where(predicateLambda).ToListAsync();
}

It throws following exception:

System.InvalidOperationException
The LINQ expression 'DbSet<SortableEntity>
    .Where(s => s.IsDeleted == False)
    .Where(s => s.Id == 123 & e.IntProperty > 456)' could not be translated.

I guess the problem is in s => s.Id == 123 & e.IntProperty > 456, one expression is using s variable name and other e variable name. How I can make it work so both expressions use same variable name?

user606521
  • 14,486
  • 30
  • 113
  • 204
  • 1
    You can also use the [ReplacingExpressionVisitor](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.query.replacingexpressionvisitor?view=efcore-5.0) class from EF Core. But the principle is one and the same. – Ivan Stoev Nov 13 '21 at 14:25
  • 1
    Gah, I'd just written an answer for the question above. You don't need the visitor, you just need to build up the property-selecting expressions correctly. – Rich N Nov 13 '21 at 14:48

0 Answers0