zoukankan      html  css  js  c++  java
  • 学习并使用了两种linq to entity 的实现sql关键字in的查询方法

    //构造Lambda语句
           private static Expression<Func<TElement, bool>> BuildWhereInExpression<TElement, TValue>(Expression<Func<TElement, TValue>> propertySelector, IEnumerable<TValue> values)
            {
                ParameterExpression p = propertySelector.Parameters.Single();
                if (!values.Any())
                    return e => false;

                var equals = values.Select(value => (Expression)Expression.Equal(propertySelector.Body, Expression.Constant(value, typeof(TValue))));
                var body = equals.Aggregate<Expression>((accumulate, equal) => Expression.Or(accumulate, equal));

                return Expression.Lambda<Func<TElement, bool>>(body, p);
            }

    //调用
          string[] ids = new string[]{"id1","id2","id3"};
          db.ProjectFiles.Where(BuildWhereInExpression<Profile,int>(v=>v.Id,ids);

    //封装方法

            public static IQueryable<TElement> WhereIn<TElement, TValue>(this IQueryable<TElement> source, Expression<Func<TElement, TValue>> propertySelector, params TValue[] values)
            {
                return source.Where(BuildWhereInExpression(propertySelector, values));
            }
    //直接使用下列方法调用

          string[] ids = new string[]{"id1","id2","id3"};
          db.ProjectFiles.WhereIn(c => c.Id,ids);
    //字符串构造
    //这个方法比较简单

          string[] ids = new string[]{"id1","id2","id3"};
          cstIds=cstIds.Replace(",","','");
          var query = db.ProjectFiles.Where("it.Id in {'" + cstIds + "'}");

  • 相关阅读:
    [YTU]_2536( C++ 长方体继承自矩形)
    [YTU]_2560(C++继承(改错题))
    [YTU]_2532(投简历)
    [YTU]_2621(B 继承 圆到圆柱体)
    stl
    noip2008双栈排序
    倍增入门水题
    noip模拟【ping】
    dp入门(LIS,LCS)
    【Luogu 1799】数列
  • 原文地址:https://www.cnblogs.com/riskyer/p/3230977.html
Copyright © 2011-2022 走看看