I'm coding a custom query builder from expressions, and at some point I'm saving the value of an expression to my criteria class:
switch(expression.NodeType)
{
case ExpressionType.Constant:
{
//Here there should only be raw values
CriteriaClass newCriteria = new CriteriaClass();
newCriteria.Value = expression; //Value is of 'object' type
return newCriteria;
}
}
And when I'm actually setting up the query, I have a list of all criterias and their values, which seem fine but... their types are all messed up. The problem is that my next step is converting properly the types of values to the specific DB format:
private string FormatWriteValue(object value, Type type)
{
if (value == null) { return "NULL"; }
if (value.GetType().IsEnum) { return ((int)value).ToString(); }
switch(type.Name)
{
case "Boolean":
case "bool":
return ((bool)value) ? "1" : "0";
case "Int32":
case "int":
return value.ToString();
case "DateTime":
return "CONVERT(DATETIME, '" + ((DateTime)value).ToString("dd/MM/yyyy hh:mm:ss") + "', 103)";
default:
return "'" + value.ToString().Replace("'", "''") + "'";
}
}
Since the type is never one of the basic ones I've typed there, it always falls on the default case for strings. I've tried casting the value of the expression like this:
criteria.Value = (int)expression; //exception
criteria.Value = Convert.ChangeType(expression, expression.Type); //Type = Int32, but exception again
criteria.Value = Expression.Convert(expression, expression.Type); //Becomes Unary, no exception
I think for the last one to work I'd have to compile the expression, but I've read that it's costly and I'd like to keep this as light as possible.
How can I accomplish this?