Evaluating an expression stored as a string
I want to store a boolean expression in a database, and evaluate it. It’s not necessary to store the complete expression tree, a string probably do it.
I imagined a scheme like this: Criteria (expression_to_evaluate, value_to_return)
For example, let’s say that I have an expression that matches people with age between 20 and 40:
(var >= 20 AND var <= 40)
var
would have to be subst开发者_如何学JAVAituted with the age of the person in question, and if there’s a match it should return that row. If it doesn’t match, the next row should be considered, evaluating that expression, and so on.
There can be more complicated expressions such as:
((var >= 20 AND var <= 40) OR (var < 10))
Maybe even with two variables:
((var1 <= 10) AND (var2 >= 10 OR var1 == 20))
This should be done in either SQL (SQL Server 2005/2008) or C#. The value of the matching row, should be returned and further processed in C#.
Is this even possible?
EXECUTE
| EXEC
allows you to first build a string of T-SQL and then execute it. You could perform logic to first build your string depending on your variables, then simply EXEC
it.
Along the same lines, you can do the same in C#, and execute the T-SQL using ExecuteNonQuery()
or ExecuteReader()
.
Use the System.Linq.Dynamic stuff, which is deeply hidden in the Visual Studio code samples, together with the normal linq-to-sql. The specified property names are mapped against the generated entity class.
myContext.MyTable.Where("Property > 20 && Property < 40").ToList();
精彩评论