Search code examples
c#linqlambdaexpression

Conversion from Expression<Func<T, bool>> to string


I need to convert Expression<Func<T, bool>> to string. How can I do it? This is the predicate I'm trying to convert:

var prezziList = ExecQuery<Listino>(i => i.CodArt == articolo.CodArt);

I'm using the method suggested here: Converting Expression<T, bool> to String, and this is my method:

public List<TEntity> ExecQuery<TEntity>(Expression<Func<T, bool>> predicate)
{
    string expBody = predicate.Body.ToString();

    var paramName = predicate.Parameters[0].Name;
    var paramTypeName = predicate.Parameters[0].Type.Name;
    expBody = expBody.Replace(paramName + ".", paramTypeName + ".")
                 .Replace("AndAlso", "&&")
                 .Replace("==", "=");

    SQLiteCommand sQLiteCommand = new(App.CNManager.Connection);
    sQLiteCommand.CommandText = $"SELECT * FROM myTable WHERE {expBody}";

    return sQLiteCommand.ExecuteQuery<TEntity>();
}

but it returns following string, which obviously is not in the correct format:

"Listino.CodArt = value(Vendo.ViewModels.DettaglioArticoliViewModel+<>c__DisplayClass184_0).articolo.CodArt"

Where am I doing wrong?


Solution

  • As Steve Wilkes said in this post you can use AgileObjects.ReadableExpressions.

    After installing Package Using following command:

    PM> Install-Package AgileObjects.ReadableExpressions
    

    You can use it in this way

    using AgileObjects.ReadableExpressions;
    
    string readable = myExpression.ToReadableString();