Reputation: 656
I am using Lamda expressing to combine condition for Where clause in enity framework This is my code : The binary operator AndAlso is not defined for the types 'System.Boolean
private Expression<Func<Transaction, bool>> BuildFilter(MovementFilterModel filterModel)
{
Expression<Func<Transaction, bool>> expr = c => true;
if (filterModel.BankAccounts.Count > 0)
{
foreach (var bank in filterModel.BankAccounts)
{
Expression<Func<Transaction, bool>> newPred = c => c.BankAccountId == Guid.Parse(bank);
expr = Expression.Lambda<Func<Transaction, bool>>(Expression.AndAlso(expr, newPred), expr.Parameters);
}
}
if (filterModel.Type == Enum.MovementType.EXPENSES)
{
Expression<Func<Transaction, bool>> newPred = c => c.Amount < 0;
expr = Expression.Lambda<Func<Transaction, bool>>(Expression.AndAlso(expr.Body, newPred), expr.Parameters);
}
else if (filterModel.Type == Enum.MovementType.INCOME)
{
Expression<Func<Transaction, bool>> newPred = c => c.Amount >= 0;
expr = Expression.Lambda<Func<Transaction, bool>>(Expression.AndAlso(expr, newPred), expr.Parameters);
}
if (filterModel.StartDate != null)
{
Expression<Func<Transaction, bool>> newPred = c => c.MadeOn >= filterModel.StartDate;
expr = Expression.Lambda<Func<Transaction, bool>>(Expression.AndAlso(expr, newPred), expr.Parameters);
}
if (filterModel.EndDate != null)
{
Expression<Func<Transaction, bool>> newPred = c => c.MadeOn <= filterModel.EndDate;
expr = Expression.Lambda<Func<Transaction, bool>>(Expression.AndAlso(expr, newPred), expr.Parameters);
}
if (filterModel.Category.Subcategories.Count > 0)
{
foreach (var subc in filterModel.Category.Subcategories)
{
Expression<Func<Transaction, bool>> newPred = c => c.SubCategoryId == Guid.Parse(subc);
expr = Expression.Lambda<Func<Transaction, bool>>(Expression.AndAlso(expr, newPred), expr.Parameters);
}
}
return expr;
}
When i call the function i get the exception : The binary operator AndAlso is not defined for the types 'System.Boolean. Any Solution please
Upvotes: 0
Views: 3811
Reputation: 4634
Try changing from this:
expr = Expression.Lambda<Func<Transaction, bool>>(Expression.AndAlso(expr.Body, newPred), expr.Parameters);
To this:
expr = Expression.Lambda<Func<Transaction, bool>>(Expression.AndAlso(expr, newPred), expr.Parameters);
(Change expr.Body
to expr
)
Upvotes: 3