C#实体框架在不能为空的字段的过滤器之后选择max [英] C# Entity Framework select max after where filter of not nullable field

查看:196
本文介绍了C#实体框架在不能为空的字段的过滤器之后选择max的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a 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()的结果为null,所以Max()的结果将为null,但是当Num不可为空时,就会发生异常.

the problem occurred when there wasn't any record of category == "A" . Because the result of Where() is null so the result of Max() will be null but when Num is not nullable the exception occurred.

我可以通过在表设计中将Num设置为可为空来修复它,但是我不喜欢这种解决方案,而Num应该具有值并且不应为可为空.

I can fix it by setting Num as nullable in table design but I don't like this solution while Num should has value and shouldn't be nullable.

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

Any suggestion? Is there a way that I accept null value for Num while Num is not nullable? or any better query?

推荐答案

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

请参阅:如果为空查询,则为最大返回值

这篇关于C#实体框架在不能为空的字段的过滤器之后选择max的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆