将“fieldname .startsWith。'fieldValue'”转换为.Where(p => p.fieldname.StartsWith('fieldValue'))谓词?

时间:2010-10-31 22:22:12

标签: c# entity-framework-4 lambda expression-trees

我尝试在下面这样做,因为它变得复杂而心灵空白。

我需要构建一个谓词,从客户端字符串传递到我的产品库:

"fieldname .startsWith. 'fieldvalue'"
"fieldname .contains. 'fieldvalue'"
"fieldname .equals. 3"
"fieldname .greaterThan. 3"
"fieldname .lessThan. 3"

字段名称可以是实体中的任何现有字段。它完全匹配它们的工作。只有数字和字符串,只列出了命令。

到目前为止

代码(狂野抨击):

// p => p.L == R
// L is the left side (the field to examine)
// R is the right side (the value to compare to)
// O is the operator (Equal)

var fieldParm    = Expression.Parameter(typeof(Entity), typeof(Entity).Name);

var compareL1 = MemberExpression.Property(fieldParm, "fieldName"); // fieldname
var compareR1 = Expression.Constant("fieldValue");  // what field should equal
var compareO1 = MemberExpression.Equal(compareWhat, compareTo);

// Do it again for each one (probably should make a foreach out of this)
var compareL2 = MemberExpression.Property(fieldParm, "fieldName"); // fieldname
var compareR2 = Expression.Constant("fieldValue");  // what field should equal
var compareO2 = MemberExpression.Equal(compareWhat, compareTo);

// Put them all together
var myExpress = Expression.And(compareO1, compareO2) // And them together

// Create predicate
Expression<Func<Entity, bool>> resultLambda =
    Expression.Lambda<Func<Entity, bool>>( myExpress,
        new ParameterExpression[] { fieldParm });

resultLambda应该包含我们的谓词以传递给我们的.Where()子句

您如何为上述一系列AND条件执行此操作?

0 个答案:

没有答案