henkmollema / Dommel

CRUD operations with Dapper made simple.
MIT License
634 stars 100 forks source link

Suggestion: CAST visitation from ToString method #241

Closed hasancemcerit closed 2 years ago

hasancemcerit commented 4 years ago

I've recently had a use case where I need to have LIKE query on a numeric column. What I ended up doing is to expand VisitCallExpression(MethodCallExpression expression) with another case (tostring) as below.

 case "tostring":
            return VisitCastExpression(expression);

and create VisitCastExpression

protected virtual object VisitCastExpression(MethodCallExpression expression)
{
    var column = VisitExpression(expression.Object);
    if (expression.Arguments.Count >= 1)
    {
        throw new ArgumentException("Cast-expression should not contain any argument.", nameof(expression));
    }

    return $"CAST({column} AS CHAR)";
}

This is working fine on MariaDB and MySQL.

The lamda expression such as

i => ((i.TextColumn1.StartsWith("1234") AndAlso i.TextColumn2.StartsWith("567")) AndAlso i.DecimalColumn1.ToString().StartsWith("555"))

becomes

select * from table where (TextColumn1 like '1234%' and TextColumn2 like '567%' and CAST(DecimalColumn1 AS CHAR) like '555%') order by id asc limit 0, 20
henkmollema commented 3 years ago

@hasancemcerit can you create a PR for this?