实体框架组和处理空值

问题描述 投票:1回答:1

我试图从数据库表CustomerComplaintExpenseRows中返回月度总和。因为我需要月度值,即使它是0,我必须用sum查询来分组月度范围。在var q cc.sum中,有些月份可能是空的,而且十进制数据类型不接受"??0 "操作。我怎样才能让我的代码在值为空时返回0?

var firstDayOfYear = new DateTime(DateTime.Now.Year, 1, 1);
var lastDayOfYear = new DateTime(DateTime.Now.Year, 12, 31);

var months = Enumerable.Range(1, 12)
            .Select(month => month)
            .ToList();

var complaints = _context.CustomerComplaintExpenseRows
                   .Where(a => a.CustomerComplaint.ComplaintDate > firstDayOfYear 
                            && a.CustomerComplaint.ComplaintDate < lastDayOfYear)
                   .GroupBy(o => o.CustomerComplaint.ComplaintDate.Month)
                   .Select(a => new
                   {
                       a.Key,
                       sum = a.Sum(i => i.RowValue)
                   })
                   .ToList();

var q = from m in months
        join cc in complaints on m equals cc.Key into joined
        from cc in joined.DefaultIfEmpty()
        select new
        {
            name = CultureInfo.CreateSpecificCulture("fi-FI")
                        .DateTimeFormat
                        .GetAbbreviatedMonthName(m),
            value = cc.sum
        };

我正在寻找的结果示例。

[
    {
    "name": 'Jan',
    "value": 300,00
    },
    {
    "name": 'Feb',
    "value": 0,00
    },
    {
    "name": 'Mar',
    "value": 5,30
    },
]
entity-framework linq asp.net-core
1个回答
0
投票

只是为了完整

设定值是这样的

value = (cc.sum == null)? 0: cc.sum
© www.soinside.com 2019 - 2024. All rights reserved.