在 ASP.NET Core-5 Web API 中,我有以下代碼:
public class DashboardCountDto
{
public int? AllMandateCount { get; set; }
public int? CurrentYearMandateCount { get; set; }
}
public List<DashboardCountDto> GetDashboardFieldCount()
{
DashboardCountDto data = new DashboardCountDto();
DateTime current = DateTime.Now;
data.CurrentYearMandateCount = _context.zib_mandates.Where(m => m.CreatedDate == current.Year).Select(c => c.Id).Distinct().Count();
List<DashboardCountDto> dataCount = new List<DashboardCountDto>();
dataCount.Add(data);
return dataCount;
}
CreatedDate 是 DateTime 資料型別
這是回傳當前年份的記錄數。
我收到了這個錯誤:
運算子“==”不能應用于“日期時間”型別的運算元?和'int'
我該如何糾正這個問題?
謝謝
uj5u.com熱心網友回復:
在你的行中你寫
data.CurrentYearMandateCount = _context.zib_mandates.Where(m => m.CreatedDate == current.Year).Select(c => c.Id).Distinct().Count();
但是CreatedDate 是 Date 型別, current.Year 是 int 型別。所以如果你與年份比較你應該寫
data.CurrentYearMandateCount = _context.zib_mandates.Where(m => m.CreatedDate.Year == current.Year).Select(c => c.Id).Distinct().Count();
希望它有效
uj5u.com熱心網友回復:
試試看:
public List<DashboardCountDto> GetDashboardFieldCount()
{
DashboardCountDto data = new DashboardCountDto();
DateTime current = DateTime.Now;
DateTime currentYear= DateTime.Parse($"{current.Year}/01/01");
data.CurrentYearMandateCount = _context.zib_mandates.Where(m => m.CreatedDate >= currentYear).Select(c => c.Id).Distinct().Count();
List<DashboardCountDto> dataCount = new List<DashboardCountDto>();
dataCount.Add(data);
return dataCount;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/416845.html
標籤:
上一篇:在控制器中獲取當前用戶
