In my ASP.NET Core Web API, I have this code.
public class PagingDto
{
public int PageSize { get; set; }
public int PageNumber { get; set; }
}
public class TransactionFilter : PagingDto
{
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public string SearchQuery { get; set; }
}
GetAllTransactions
public IQueryable<Transaction> GetAllTransactions(TransactionFilter filter)
{
var transactions = _context.Transactions
.Where(x => x.CreatedDate.Date >= filter.StartDate && x.CreatedDate.Date <= filter.EndDate)
.Where(x => string.IsNullOrEmpty(filter.SearchQuery) || x.Customer.Name.ToLower().Contains(filter.SearchQuery.ToLower())
|| x.Payment.Status.ToLower().Contains(filter.SearchQuery.ToLower())
|| x.Payment.TransactionReference.ToLower().Contains(filter.SearchQuery.ToLower())
|| x.Payment.MethodOfPayment.ToLower().Contains(filter.SearchQuery.ToLower())
|| x.Payment.Amount.ToString().Contains(filter.SearchQuery))
.Include(b => b.Payment)
.Include(b => b.Customer)
.OrderByDescending(transaction => transaction.CreatedDate);
return transactions;
}
I want to Query all transactions that falls between StartDate and EndDate using CreatedDate.
But I got thus error:
Severity Code Description Project File Line Suppression State
Error CS1061 'DateTime?' does not contain a definition for 'Date' and no accessible extension method 'Date' accepting a first argument of type 'DateTime?' could be found (are you missing a using directive or an assembly reference?)
Then Date is highlighted in
.Where(x => x.CreatedDate.Date >= filter.StartDate && x.CreatedDate.Date <= filter.EndDate)
How do I resolve this?
Thanks
>Solution :
DateTime?
is an equivalent of Nullable<DateTime>
.
Nullable<T>
doesn’t have a property .Date
.
You should write:
x.CreatedDate.Value.Date
But you should keep in mind that x.CreatedDate
can be null
in the runtime. In that case, youll get a
NullReferenceExpection`.
So, your logic should support such a case and should contain additional checks not to call x.CreatedDate.Value.Date
when x.CreatedDate
is null
.
Useful links: