简体   繁体   English

使用实体框架在Linq中动态放置

[英]Dynamic Where in Linq with Entity Framework

i wrote function 我写了函数

    private Func<CategorizedPosts, bool> CompileExpression(IEnumerable<Category> categories)
    {
        Expression predicateBody;
        ParameterExpression pe = Expression.Parameter(typeof(CategorizedPosts), "post");
        Expression left = Expression.Property(pe, typeof(CategorizedPosts).GetProperty("CATEGORY_ID"));
        Expression right = Expression.Constant(categories.ElementAt(0).ID);
        Expression equal = Expression.Equal(left, right);
        predicateBody = equal;
        for (int i = 1, j = categories.Count() - 1; i < categories.Count(); ++i )
        {
            var category = categories.ElementAt(i);
            //y => y.CATEGORY_ID == 1 || y.CATEGORY_ID == 2)
            left = Expression.Property(pe, typeof(CategorizedPosts).GetProperty("CATEGORY_ID"));
            right = Expression.Constant(category.ID);
            equal = Expression.Equal(left, right);

            predicateBody = Expression.OrElse(predicateBody, equal);
        }

        var lll = Expression.Lambda<Func<CategorizedPosts, bool>>(predicateBody, pe);
        var compiled = lll.Compile();
        return compiled;
    }

it compiles OK, but when I try to run this query 它可以编译,但是当我尝试运行此查询时

            var ctx = db.Posts.Where(x => true);
            if(predicate != null)
            {
                ctx = ctx.Where(x => x.CategorizedPosts.Where(**predicate**).Count() > 0);
            }
            IList<Post> posts = ctx.OrderByDescending(x => x.CREATION_DATE).Skip((page - 1) * perPage).Take(perPage).Select(x => new Post 
            {
                POST_ID = x.ID,
                TYPE = new Type { ID = x.TYPE_ID, NAME = x.Types.NAME },
                AUTHOR = new Author()
                {
                    ID = x.AUTHOR_ID,
                    NAME = x.Authors.NAME,

                },
                CATEGORIES = x.CategorizedPosts.Select(y => new Category() { ID = y.CATEGORY_ID, NAME = y.Categories.NAME }),
                CREATION_DATE = x.CREATION_DATE,
            }).ToList();

EF throws exception about internal error 1025 for Entity Data Provider. EF引发有关实体数据提供程序内部错误1025的异常。 How can I perform this query with dynamic where? 如何在动态位置执行此查询?

You could use the Contains of a collection of Ids ( int ) and apply it on a where, for sample: 您可以使用Ids集合( int )的Contains并将其应用于where,作为示例:

int[] categorieIds = categories.Select(x => x.Id).ToArray();

ctx = ctx.Where(x => x.CategorizedPosts.Any(c => categorieIds .Contains(c.Id));

Some Tips 一些技巧

Remember the Entity Framework works with Expression<Func<T, bool>> in the Where method, not only Func<T, bool> . 还记得实体框架的工作原理与Expression<Func<T, bool>>Where方法,不仅Func<T, bool>

You also could try to apply PredicateBuilder class which provides some extensions methods like Or , And , Not , so, you could try this: 您还可以尝试应用PredicateBuilder类,该类提供了一些扩展方法,例如OrAnd Not ,因此,您可以尝试以下操作:

  var predicate = PredicateBuilder.False<Product>();

  foreach (string keyword in keywords)
  {
    string temp = keyword;
    predicate = predicate.Or (p => p.Description.Contains (temp));
  }

  return dataContext.Products.Where(predicate).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM