通用EF存储库

时间:2011-07-08 05:26:29

标签: .net entity-framework linq sql-like

我的EF有一个通用存储库。它工作得非常好。但是今天我发现我需要获得不完全匹配的结果,而应该像SQL的'LIKE',它获取具有匹配后缀或列前缀的任何内容。现在它的作用是平等算子。我如何调整此代码以表现得像LIKE而不是相等?

public IList<TEntity> SelectManyByColumnKeywordLike(string Key, string columnName)
{

    // First we define the parameter that we are going to use the clause. 
    var xParam = Expression.Parameter(typeof(TEntity), typeof(TEntity).Name);
    MemberExpression leftExpr = MemberExpression.Property(xParam, columnName);
    Expression rightExpr = Expression.Constant(Key);
    BinaryExpression binaryExpr = MemberExpression.Equal(leftExpr, rightExpr);
    //Create Lambda Expression for the selection 
    Expression<Func<TEntity, bool>> lambdaExpr =
    Expression.Lambda<Func<TEntity, bool>>(binaryExpr,
    new ParameterExpression[] { xParam, });
    //Searching ....
    IList<TEntity> resultCollection = ((IADRRepository<TEntity, TContext>)this).SelectAll
                (new Specification<TEntity>(lambdaExpr));
    if (null != resultCollection && resultCollection.Count() > 0)
    {
        //return valid single result 
        return resultCollection;
    }//end if 
    return null;
}

1 个答案:

答案 0 :(得分:2)

Like在linq-to-entities中表示为:

  • Contains("something")代表LIKE '%something%'
  • EndsWith("something")代表LIKE '%something'
  • StartsWith("something")代表LIKE 'something%'

因此,您的方法需要知道要使用的LIKE类型,并创建正确的表达式来表示:

  • context.YourEntities.Where(e => e.Column.Contains(key))
  • context.YourEntities.Where(e => e.Column.EndsWith(key))
  • context.YourEntities.Where(e => e.Column.StartsWith(key))