Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to DateTime in C# EF Core query

Tags:

var res = Context.Exampletable
                 .Where(s => s.CompanyId == CompanyId &&  
                             Convert.ToDateTime(s.TextDate) >= DateTime.Now)
                 .Select(x => new Exampletable { TextDate = x.TextDate })
                 .FirstOrDefault();

This is the Linq for one of my problem statements. I want to fetch records future date records from current date & timestamp, so I am converting and comparing it to Datetime but I get this error:

The LINQ expression 'DbSet
.Where(a => Convert.ToDateTime(a.TextDate) > Convert.ToDateTime(DateTime.Now))' > could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()

Note: in Postgresql DB TextDate column has string datatype and contains values like '4/1/2020 10:00 AM'.

Please provide a solution for this.

like image 669
TedS Avatar asked Apr 01 '20 10:04

TedS


People also ask

What is Strptime in C?

The strptime() function converts the character string pointed to by buf to values that are stored in the tm structure pointed to by tm, using the format specified by format. The format contains zero or more directives.

What is ParseExact C#?

ParseExact(String, String, IFormatProvider) Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

How do I fix string is not recognized as a valid DateTime?

By parsing the string representation of a date and time value. The Parse, ParseExact, TryParse, and TryParseExact methods all convert a string to its equivalent date and time value. The following example uses the Parse method to parse a string and convert it to a DateTimevalue.


1 Answers

If you really can't change the underlying column type, then instead of unsupported Convert.ToDateTime use C# cast operator which maps to PostgreSQL CAST operator:

(DateTime)(object)s.TextDate >= DateTime.Now

Note that the "intermediate" cast to object is needed just to make the C# compiler happy.


P.S. I really have no idea why some methods of Convert like ToInt32 are supported, and other like ToDateTime are not. I guess just yet another EF Core inconsistency.

like image 175
Ivan Stoev Avatar answered Sep 30 '22 21:09

Ivan Stoev