Home > Net >  What does casting a string to DateTime in an Entity Framework Core LINQ query return?
What does casting a string to DateTime in an Entity Framework Core LINQ query return?

Time:12-01

My application uses Entity Framework Core to load data from an SQL database. To avoid loading all data entries of my table Schedule and filter them afterwards, I would like to filter them in the database query by comparing the Schedule.Date entry, which is a string, to a previously created DateTime object named targetDate. Since it is not possible to directly use DateTime.Parse to convert Schedule.Date to a DateTime in this query, I instead cast it to an object and then DateTime explicitly. The following line represents what I'm doing:

Schedule schedule = _context.Schedule.Where(s => (DateTime)(object)s.Date >= targetDate).First();

This works fine for now. However, I don't want to run into problems later, so I need to understand which format the cast to DateTime uses in this case. Though the dates in the database are strings, they are all provided in the format en-US and casting them appears to use just this format, which would be great. How can I be sure that it always uses this format and how is the format to be used determined when using a cast like this?

CodePudding user response:

Assuming you are using SQL Server

Though the dates in the database are strings,

Which is bad for a number of reasons. Here you'll require a table scan to convert all the strings to dates to perform the comparison.

they are all provided in the format en-US and casting them appears to use just this format, which would be great. How can I be sure that it always uses this format and how is the format to be used determined when using a cast like this?

The conversion is done in SQL Server which will convert strings to dates based on the current language of the connection.

  • Related