Home > database >  ASP.NET Core - How to get Registered Customer Per Month in the Current Year
ASP.NET Core - How to get Registered Customer Per Month in the Current Year

Time:01-27

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

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;
}

I want to count the registered customer for each month in the current year, and get the result as shown below:

CustomerCount    Month

5                 Jan
4                 Feb
9                 Mar

till December. But I got this error:

'DateTime?' does not contain a definition for 'Month' and no accessible extension method 'Month' accepting a first argument of type 'DateTime?' could be found (are you missing a using directive or an assembly reference?)

And it highlights Month in o.CreatedDate.Month

How do I resolve this?

Thanks

CodePudding user response:

The error is pretty clear: you've declared the CreatedDate property as a Nullable<DateTime>.

Nullable value types - C# reference | Microsoft Docs

A Nullable<DateTime> value does not have a Month property, so customer.CreatedDate.Month cannot be compiled.

Your m.CreatedDate >= currentYear filter will exclude entries where CreatedDate is null, so you simply need to access customer.CreatedDate.Value.Month instead.

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