C#表达式返回TSQL Contains关键字

时间:2014-05-30 16:33:25

标签: c# sql .net lambda expression-trees

我有以下代码:

public Expression FilterString(string property, string Value, ParameterExpression parameter)
{
    var getname = Expression.Property(parameter, property);

    var toLower = Expression.Call(getname, "ToLower", null, null);

    var contains = Expression.Call(toLower, "Contains", null, new[] { Expression.Constant(Value.ToString().ToLower()) });

    //This will result in "LOWER(Body) LIKE '%abc123% " but I need "CONTAINS(Body, 'abc123')"

    return contains;
}

var parameter = Expression.Parameter(typeof(Message), "message");
var expressionFilter = myclass.FilterString("Body","abc123", parameter);
var lambda = Expression.Lambda(expressionFilter, parameter);

//Apply lambda to EF query object
query = query.Where((Expression<Func<Message, bool>>)lambda);

这会生成一个TSQL LIKE语句,但我希望它能够执行CONTAINS语句。

无论如何我可以修改上面的FilterString方法来做到这一点吗?

2 个答案:

答案 0 :(得分:1)

看起来你可以使用香草EF,至少根据这里的消息来源:http://entityframework.codeplex.com/SourceControl/latest#src/EntityFramework/Core/Common/EntitySql/AST/BuiltInKind.cs

您必须将AST添加到AST并生成它。 Here's a basic tutorial on DBProviders.

答案 1 :(得分:0)

我意识到这并不是你想要的,但你应该能够通过让自己走出LINQ并直接查询数据库来轻松获得你想要的结果:

MyDbContext.Database
.SqlQuery<MyTable>("select * from [MyTable] where contains(Body, @p0), "abc123")