简体   繁体   中英

How do I convert varchar(20) in SQL Server to datetime in C#?

I'm storing dates in SQL Server as varchar so they become strings in C# by Entity Framework.

Then I tried to convert then to date but the code throws an exception.

In SQL Server:

CREATE TABLE [dbo].[Achievements]
(
      ...   
      [DatePerformance] [VARCHAR](20) NULL, 
)

The date is stored in this format: "25/04/2019"

In C#:

public static School_LPEntities db = new School_LPEntities();

I tried:

List<Achievements> res = db.Achievements.Where(x =>  DateTime.Parse(x.DatePerformance) <= DateTime.Today.Date).ToList();

and:

List<Achievements> res = db.Achievements.Where(x =>   DateTime.ParseExact(x.DatePerformance, "dd/MM/yyyy",
 CultureInfo.InvariantCulture) <= DateTime.Today.Date).ToList();

The code throws:

System.NotSupportedException: 'LINQ to Entities does not recognize the method 'System.DateTime Parse(System.String)' method, and this method cannot be translated into a store expression.'

As others have said in the comments, the number of good reasons to store your dates as varchar's in SQL is zero.

You said:

so they become strings in C# by Entity Framework

Once you get the date in C# you can do this easily anyway with a .ToString() .

But... as to your specific error, what it's telling you is that you can't use this method inside of an Entity Framework LINQ statement. It's best to think of LINQ statements as queries. Because, in fact, it needs to be able to convert your LINQ statement into an actual SQL query. You can't use DateTime.Parse() inside of a SQL query, so it throws this error.

If you really MUST store your dates as varchar's in the database (and again, this is a terrible idea) then I'm not seeing a really simple solution. Off hand, I would tell you to first, create your list, then loop through it:

List<Achievements> res = db.Achievements.ToList();

Then:

foreach (var achievement in res)
{
   if (DateTime.Parse(achievement.DatePerformance)  <= DateTime.Today.Date)
   {
       // do something here
   }
}

But this is a really clunky way to work around the real solution: Just store your dates as dates!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM