在我的 ASP.NET Core-5 Web API 中,我有這個模型:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public DateTime? CreatedDate { get; set; }
}
DTO:
public class MonthlyCountDto
{
public int CustomerCount { get; set; }
public string Month { get; set; }
}
public List<MonthlyCountDto> GetCustomerMonthlyCount()
{
DateTime current = DateTime.Now;
DateTime currentYear = DateTime.Parse($"{current.Year}/01/01");
var regDetail = _context.customers.Where(m => m.CreatedDate >= currentYear)
.GroupBy(o => new
{
Month = o.CreatedDate.Month
})
.Select(u => new MonthlyCountDto
{
CustomerCount = u.Count(),
Month = u.FirstOrDefault().CreatedDate.Month.ToString()
}).ToList();
return regDetail;
}
我想統計當年每個月的注冊客戶,得到的結果如下圖:
CustomerCount Month
5 Jan
4 Feb
9 Mar
到十二月。但我得到了這個錯誤:
'約會時間?' 不包含“月份”的定義,并且沒有可訪問的擴展方法“月份”接受“日期時間”型別的第一個引數?可以找到(您是否缺少 using 指令或程式集參考?)
它在 o.CreatedDate.Month 中突出顯示月份
我該如何解決這個問題?
謝謝
uj5u.com熱心網友回復:
錯誤很明顯:您已將該CreatedDate屬性宣告為Nullable<DateTime>.
可空值型別 - C# 參考 | 微軟檔案
值Nullable<DateTime>沒有Month屬性,因此customer.CreatedDate.Month無法編譯。
您的m.CreatedDate >= currentYear過濾器將排除 where CreatedDateis 的條目null,因此您只需要訪問即可customer.CreatedDate.Value.Month。
var regDetail = _context.customers
.Where(m => m.CreatedDate >= currentYear)
.GroupBy(o => new
{
Month = o.CreatedDate.Value.Month
})
.Select(u => new MonthlyCountDto
{
CustomerCount = u.Count(),
Month = u.Key.Month.ToString()
}).ToList();
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/422422.html
標籤:
