顺序通过与条件的关系的子集

本文关键字:关系 子集 条件 顺序 | 更新日期: 2023-09-27 18:30:52

我试图通过Bars.Max(Date)没有OptionalBars子集来订购Foo

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

// 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
}

顺序通过与条件的关系的子集

Bar.Optional是一个集合,而不是单个引用。不能将集合与 LINQ 到实体的null进行比较。相反,您必须按Optional集合没有!) 具有 Any 元素的Bars进行过滤:

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

您可能有必要使用 Max(b => (DateTime?)b.Date) 而不仅仅是 Max(b => b.Date) 来解释FooBars集合可能为空并因此没有最大Date的可能情况。我不是100%确定。应显式测试空Bars集合的情况。

  Foo.OrderBy(f => f.Bars
 .Where(b => b.Optional == null).AsEnumerable().
 .Max(b => b.Date));

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

Foo.OrderBy(f =>f.Bars.Where(x => x.Optional == null)
                                        .Max(x => x.Date)));