I want to build Dapper string using a LINQ expression as method argument. I've found at MS Docs an example of parsing and integrated it in my code:
public static List<Notification> GetNotifs(Expression<Func<Notification, bool>> p)
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
string sqlQ = "SELECT * FROM Notifications WHERE ";
ParameterExpression param = p.Parameters[0];
BinaryExpression operation = (BinaryExpression)p.Body;
ParameterExpression left = (ParameterExpression)operation.Left;
for (int i = 0; i < left.Name.Length; i++) { if (i <= param.Name.Length) { } else { sqlQ += left.Name[i]; } }
ConstantExpression right = (ConstantExpression)operation.Right;
if (operation.NodeType.ToString() == "LessThan") sqlQ += " <";
else if (operation.NodeType.ToString() == "GreaterThan") sqlQ += " >";
else if (operation.NodeType.ToString() == "LessThanOrEqual") sqlQ += " <=";
else if (operation.NodeType.ToString() == "GreaterThanOrEqual") sqlQ += " >=";
else if (operation.NodeType.ToString() == "Equal") sqlQ += " =";
else if (operation.NodeType.ToString() == "NotEqual") sqlQ += " !=";
sqlQ += " " + right.Value;
return connection.Query<Notification>(sqlQ).ToList();
}
}
But, unfortunately it gives an InvalidCastException at the
ParameterExpression left = (ParameterExpression)operation.Left;
The call of this method is like:
DRepository.GetNotifs(uid => uid.U_Id == id)
Could you help me to find out, where am I incorrect?