2

Is there a way to translate predicate(Func<T,bool>) using LINQ to SQL query or something similar to this?

Found nothing on internet or MS guides.

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
  • For translating predicate you have to use `Expression>`. But without mapping information it is bad idea to implement it by hands. – Svyatoslav Danyliv Jan 24 '23 at 20:11
  • @SvyatoslavDanyliv, thanks, but my goal is to create a basic CRUD and I want to make it without any side libraries or frameworks, just with basic linq, so i found this example : https://stackoverflow.com/questions/7731905/how-to-convert-an-expression-tree-to-a-partial-sql-query/7891426#7891426 – Maksym Shchehel Jan 25 '23 at 20:05

2 Answers2

1

ORMs (like Entity Framework, linq2db, and others) in C# usually use expression trees and IQueryable to be able to translate the code into actual SQL queries, so they need Expression<Func<T, bool>>, not just Func<T, bool>. If you are creating the predicate via lambda then compiler can also translate it to expression tree, i.e.:

Func<MyClass, bool> predicate = mc => mc.IntProp == 1;
Exppression<Func<MyClass, bool>> predicate = mc => mc.IntProp == 1;

Will work both well. So in some cases you can just change your method parameter and that's it.

Read more:

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
0

Short awnser : no Long awnser : yes... but actually no

There is no way to accuratly translate a programming language into another without the risk of the function and meaning being altered (you could use this but even that is no longer mantained)

I would recommend you learning LinQ in order to safely translate it without mistakes. You could also post you query so anyone like me or other more fitted members to help you out in the translation.