0

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?

Innova
  • 334
  • 4
  • 18
  • 5
    Wouldn't it be better to use Entity Framework or Dappr or another ORM than this manual hack of modifying expressions? – Camilo Terevinto Dec 07 '21 at 08:44
  • 1
    You're looking for [ExpressionVisitor](https://khalidabuhakmeh.com/linq-expression-visitors) – phuzi Dec 07 '21 at 08:57
  • The title in both questions is wrong, and the source of your problems. You don't convert expressions to strings. You're asking how to convert an expression tree to a specific language, SQL. There are infinite languages that can be generated for a single expression tree. The answer is to use a visitor that understands both the expression tree and the target language and emits whatever you want in the target language. – Panagiotis Kanavos Dec 07 '21 at 09:07

1 Answers1

0

The difference between your example and that question is, your condition is a variable articolo.CodArt, the condition in that answer is a const value.

Therefore you need to use some measure to get that value, simply replace with get the stringfy value of the variable.

You need to pass the object which need to get value, in your case is articolo, then call predicate.Compile().Invoke(articolo) to get the value, then translate it into SQL.

Jarvan
  • 1,135
  • 8
  • 22