Home > Enterprise >  ASP.NET Core - Operator '==' cannot be applied to operands of type 'DateTime?' a
ASP.NET Core - Operator '==' cannot be applied to operands of type 'DateTime?' a

Time:01-20

In ASP.NET Core-5 Web API I have this code:

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 is DateTime datatype

This is to return the count of records for the current year.

I got this error:

Operator '==' cannot be applied to operands of type 'DateTime?' and 'int'

How do I get this corrected?

Thanks

CodePudding user response:

In your line you write

data.CurrentYearMandateCount = _context.zib_mandates.Where(m => m.CreatedDate == current.Year).Select(c => c.Id).Distinct().Count();

But CreatedDate is Date Type and current.Year is int type. so If you compare with year you should write

data.CurrentYearMandateCount = _context.zib_mandates.Where(m => m.CreatedDate.Year == current.Year).Select(c => c.Id).Distinct().Count();

Hopefully it works

CodePudding user response:

try it:

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;
    }
  •  Tags:  
  • Related