C# Entity Framework select max after where filter of not nullable field

C# Entity Framework select max after where filter of not nullable field

我有一个不可为空的字段 (Num)

class MyTable
{
    //...
    public int Num { get; set; }
    public string Category { get; set; }
    //...
}

想要找到 Category == "A"

的最大值 Num
var maxnum = myTable
   .Where(r => r.Category == "A")
   .Max(r => r.Num);

category == "A"没有任何记录时出现问题。因为 Where() 的结果为空,所以 Max() 的结果将为空,但是当 Num 不可为空时,会发生异常。

我可以通过在 table 设计中将 Num 设置为可为空来修复它,但我不喜欢这个解决方案,而 Num 应该有价值并且不应该为空。

有什么建议吗?有没有一种方法可以在 Num 不可为空时接受 Num 的空值?或任何更好的查询?

int maxShoeSize = Workers.Where(x => x.CompanyId == 8)
                     .Select(x => x.ShoeSize)
                     .DefaultIfEmpty(0)
                     .Max();

参见:Max return value if empty query

Is there a way that I accept null value for Num while Num is not nullable?

当然可以:

//...
.Max(r => (int?)r.Num);

每个不可空值都可以变成可空值(但反之则不行)。我个人更喜欢这种方法(异常消息中确实建议了这种方法),因为它允许我区分无最大值和最大值 0(零)甚至 int.MinValue.

你可以试试:

var maxnum = myTable
   .Where(r => r.Category == "A")
   .Max(r => r.Num) ?? 0;

然后您可以使用 0 结果。