I want to make a function which should accept linq like expression based on model and property types of models and return a SQL string.
public class MyModel
{
public int Year { get; set; }
public string UserName { get; set; }
}
public static class MyControlClass
{
public static string BuildSQL<TModel>(Func<TModel, bool> whereExpression)
{
return $"SELECT * FROM {nameof(TModel)} WHERE {whereExpression}";
}
}
public main(){
string sqlQuery = MyControlClass.BuildSQL<MyModel>(m => m.Year == 2021 && UserName == "Tester");
//What I wish sqlQuery to be
//SELECT * FROM MyModel WHERE Year = 2021 AND UserName = "Tester"
}
Any ideas how to accomplish this? I am aware of POCO and other ORM libraries and I have been trying and searching for more than 3 days now. I just cant find a solution.