LINQ Group和SelectMany

时间:2013-03-28 17:45:00

标签: linq entity-framework

我有一个很棒的LINQ声明,Oracle不喜欢这样做:

var result = from r in Context.Accounts
        where Statuses.Contains(r.DEC_CD)
        && r.Deposit.Payments.Where(n => n.CreatedDate >= DateStart).Sum(n => n.Total - n.Fees) > 3000
        select r;

不幸的是.Where(...).Sum(...)使用Oracle EF提供程序创建了无效的SQL。

我尝试使用group重写它:

var result = from g in Context.Payment
        where g.CreatedDate >= DateStart
        group g by g.Total - g.Fees into grp
        where grp.Key >= 3000
        select g;

上面的例子没有编译。

var result = from g in Context.Payment
        where g.CreatedDate >= DateStart
        group g by g.Total - g.Fees into grp
        where grp.Key >= 3000
        select new { g };

也不编译

var result = from g in Context.Payment
        where g.CreatedDate >= DateStart
        group g by g.Total - g.Fees into grp
        where grp.Key >= 3000
        select grp.SelectMany(n => n);

看起来它可以从Intellisense工作,但我收到错误The type arguments for method SelectMany cannot be inferred from the usage 我唯一可以选择的就是grp,如果我选择的话,我会得到Igrouping<decimal, Payment>' which has keys and multiple rows underneath. I just want the rows, hence the。SelectMany`

任何想法如何得到扁平的IEnumerable<Payment>

3 个答案:

答案 0 :(得分:1)

你可能只想要这个

var result = from g in Context.Payment
    where g.CreatedDate >= DateStart
          && (g.Total - g.Fees) >= 3000
    select g;

右?所有付款总额 - 费用为gte 3000和日期标准。看来这个小组并非有意或不需要。

答案 1 :(得分:0)

var result = 
        from p in Context.Payment
        where p.CreatedDate >= DateStart
        group p by p.Total - p.Fees into g
        where g.Key >= 3000
        select g; // select group here

或者更好,没有分组:

var result = 
        from p in Context.Payment
        where p.CreatedDate >= DateStart &&
              (p.Total - p.Fees) >= 3000
        select p; 

答案 2 :(得分:0)

您必须添加from语句才能重新选择该组:

var result = from g in Context.Payment
        where g.CreatedDate >= DateStart
        group g by g.Total - g.Fees into grp
        where grp.Key >= 3000
        from i in grp
        select i;