I have the following table in SQL Server:
ProductAttribute
- Name:
nvarchar(100) - Value:
nvarchar(200)
This maps through the Entity Framework to my class:
public class ProductAttribute { public string Name {get;set;} public string Value {get;set;} }
Some ProductAttributes strings are as follows:
{Name: "RAM", Value: "8 GB"}, {Name: "Cache", Value: "3000KB"}
I need to dynamically build ExpressionTree so that it is converted to SQL , which can do the following:
If the value starts with a number followed by or not an alphanumeric string, extract the number and compare it with the given value
double value = ...; Expression<Func<ProductAttribute, bool>> expression = p => { Regex regex = new Regex(@"\d+"); Match match = regex.Match(value); if (match.Success && match.Index == 0) { matchExpression = value.Contains(_parserConfig.TokenSeparator) ? value.Substring(0, value.IndexOf(_parserConfig.TokenSeparator)) : value; string comparand = match.Value; if(double.Parse(comparand)>value) return true; } return false; }
The really annoying thing is that I need to build this expression tree dynamically .
So far I have dealt with this (this is considered a value as decimal not as a string, so it doesnβt even try to do the whole contents of regular expressions):
private Expression GenerateAnyNumericPredicate( Type type, string valueProperty, string keyValue, double value) { ParameterExpression param = Expression.Parameter(type, "s"); MemberExpression source = Expression.Property(param, valueProperty); ConstantExpression targetValue = GetConstantExpression(value, value.GetType()); BinaryExpression comparisonExpression = Expression.GreaterThan(source, targetValue); return Expression.Lambda(comparisonExpression, param); }
EDIT : With the help below, this works:
Expression<Func<ProductSpecification, bool>> expo = ps=> ps.Value.Substring(0, (SqlFunctions.PatIndex("%[^0-9]%", ps.Value + ".") ?? 0) - 1) == "1000";
But I also need a listing to double, and then a numerical comparison:
Expression<Func<ProductSpecification, bool>> expo = ps=> double.Parse(ps.Value.Substring(0, (SqlFunctions.PatIndex("%[^0-9]%", ps.Value + ".") ?? 0) - 1)) > 1000;
Obviously, this does not convert to SQL: double.Parse() .
How can I create a translation so that it can be parsed in SQL from my expression?