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

北慕城南 提交于 2019-12-24 00:47:31

问题


I have a not nullable field (Num)

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

want to find maximum Num for Category == "A"

var maxnum = myTable
   .Where(r => r.Category == "A")
   .Max(r => r.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.

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.

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


回答1:


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

See : Max return value if empty query




回答2:


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

Sure you can:

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

Every non nullable value can be turned into nullable (but not vice versa). I personally prefer this method (which acually is suggested in the exception message) because it allows me to distinguish between no max value and max value of 0 (zero) or even int.MinValue.




回答3:


You can try:

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

Then you can work with the 0 result.



来源:https://stackoverflow.com/questions/37217741/c-sharp-entity-framework-select-max-after-where-filter-of-not-nullable-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!