2

我正在尝试FooBars.Max(Date)其中Bars没有Optional.

很难用文字解释,所以这是我到目前为止得到的查询。

// Foos is of type DbSet<Foo> a "code first" EF entity
Foos.OrderBy(f => f.Bars
                  .Where(b => b.Optional == null)
                  .Max(b => b.Date));

该查询失败并显示NotSupportedException

无法比较“System.Collections.Generic.ICollection`1”类型的元素。仅支持原始类型、枚举类型和实体类型。

模型

public class Foo
{
    public int Id { get; set; }

    public virtual ICollection<Bar> Bars { get; set; } // one to many
}

public class Bar
{
    public int Id { get; set; }
    public DateTime Date { get; set; }

    public virtual Foo Foo { get; set; }
    public virtual ICollection<Optional> Optional { get; set; } // zero to many
}

public class Optional
{
    // omitted for brevity
}
4

3 回答 3

1

Bar.Optional是一个集合,而不是一个单一的参考。您无法将集合与nullLINQ-to-Entities 进行比较。相反,您必须按集合不( )具有Any元素的Bars位置进行过滤:Optional!

Foos.OrderBy(f => f.Bars
                   .Where(b => !b.Optional.Any())
                   .Max(b => b.Date));

可能有必要您必须使用Max(b => (DateTime?)b.Date)而不是仅仅Max(b => b.Date)考虑Barsa 的集合Foo可能为空并因此没有最大值的可能情况Date。我对此不是 100% 确定的。Bars您应该明确地测试空集合的情况。

于 2013-09-10T18:00:18.987 回答
0
  Foo.OrderBy(f => f.Bars
 .Where(b => b.Optional == null).AsEnumerable().
 .Max(b => b.Date));
于 2013-09-10T14:40:37.120 回答
0

鉴于您的 Foo 是 Foos 的集合,试试这个

Foo.OrderBy(f =>f.Bars.Where(x => x.Optional == null)
                                        .Max(x => x.Date)));
于 2013-09-10T14:43:32.630 回答