开发者

Generic EF repository

I have a generic repository for my EF. It is working perfectly fine. But today I found out that I need to get result that is not the exact match, instead it should be like the 'LIKE' of SQL where it gets anything that has the matching suffix or prefix of a column. Right now what it does is the Equal Operator. How can I tweak this code to behave like a LIKE instead of equal?

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;
}


Like is represented in linq-to-entities with:

  • Contains("something") for representing LIKE '%something%'
  • EndsWith("something") for representing LIKE '%something'
  • StartsWith("something") for representing LIKE 'something%'

So your method needs to know what type of LIKE you want to use and create correct expression to represent:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜