使用group by,where子句和“ HAVING”条件作为不同计数的EF查询

时间:2019-01-08 22:04:52

标签: sql-server entity-framework

我正在尝试获得与以下SQL Server查询等效的EF,在该查询中它返回具有不同产品总数超过1的所有客户的列表:

SELECT [customer]
FROM [Orders]
where product = 'foo'
OR product = 'bar'
GROUP BY customer

HAVING COUNT(DISTINCT(product)) > 1

这是我目前作为EF方法语法代码的内容:

var customerList = dbContext.GroupBy(l => l.customer)
.Select(g => new 
{ 
 Customer = g.Key, 
 Count = g.Select(l => l.product).Distinct().Count(),
 Product = g.Select(f => f.product).FirstOrDefault()
}).Where(w => w.Count > 1 && (w.Product == "foo" || w.Product == "bar"))
.Select(s => s.Customer).ToList();

这将返回如下错误列表:

  customer    Products
  --------------------
  Customer1   Foo, Bar
  Customer2   Foo, Bar
  Customer3   Foo, Bar
  Customer4   Foo, Foo

预期列表必须为:

  customer    Products
  --------------------
  Customer1   Foo, Bar
  Customer2   Foo, Bar
  Customer3   Foo, Bar

0 个答案:

没有答案