实体框架如何做或使用Linq(谓词)

时间:2012-02-16 00:47:39

标签: c# .net linq entity-framework

我正在尝试做一个OR。我以为你可以用Predicate做到这一点,所以我尝试了这个

var products = ctx.Products.Where(x => .....);

var predicate = PredicateBuilder.False<Product>();
foreach (Category categ in categs)
  predicate = predicate.Or(p => p.Categories.Select(c => c.Id).Contains(categ.Id)
                              || p.Categories.Select(c => c.Category1.Id).Contains(categ.Id)
                              || p.Categories.Select(c => c.Category1.Category1.Id).Contains(categ.Id));
products = products.Where(predicate);

但它给了我这个错误

  

System.NotSupportedException:LINQ to Entities不支持LINQ表达式节点类型“Invoke”。

有人可以帮我解决这个问题吗?谢谢你提前。

Product可以有一个或多个Category Category可能有一个名为Category1的“父类别”。上面的长3行是选择一个类别或其子类别下的产品。

我用Google搜索并找到了LinqKit,但我想避免为此添加第三方。但是,如果我必须使用LinqKit,是否易于安装?

1 个答案:

答案 0 :(得分:0)

我认为这有效

if (categs.Length > 0)
{
  List<Product> tmpProducts = new List<Product>();
  foreach (Category c in categs)
  {
    var tmp = ctx.Products.ToList().Where(x => x.IsUnderCategory(c));
    tmpProducts = tmpProducts.Union(tmp).ToList();
  }
  products = products.ToList().Intersect(tmpProducts).AsQueryable();
}

IsUnderCategory是一个扩展名

  public partial class Category
  {
    public bool IsUnderCategory(Category categ)
    {
      if (Id == categ.Id) return true; // is itself

      if (Parent == null)
        return false;

      return Parent.IsUnderCategory(categ);
    }
  }
相关问题