Reputation: 1945
I am using Linq query but getting error
Cannot apply operator >= to operands of type system.datetime and string
here is my linq query
var myBirthDate= BirthDate.ToString("yyyy-MM-dd HH':'mm':'ss");
var myList= (from myEntity in myEntityRepository.AsQueryable()
where
myEntity.id== Id &&
myEntity.birthdate >= myBirthDate
select myEntity).Take(1);
I convert date to to yyyy-MM-dd HH':'mm':'ss
format because i get in other format from client.
How can i avoid this error?
Upvotes: 0
Views: 3351
Reputation: 8177
If the date you receive is different from the current culture you can use DateTime.Parse to convert to a correct DateTime variable.
As you are using ToString to convert a DateTime type to a formatted date string, your myBirthDate variable will become a String, thus the >= won't work as expected.
Here is a sample:
using System;
public class Example
{
public static void Main()
{
string[] dateStrings = {"2008-05-01T07:34:42-5:00",
"2008-05-01 7:34:42Z",
"Thu, 01 May 2008 07:34:42 GMT"};
foreach (string dateString in dateStrings)
{
DateTime convertedDate = DateTime.Parse(dateString);
Console.WriteLine("Converted {0} to {1} time {2}",
dateString,
convertedDate.Kind.ToString(),
convertedDate);
}
}
}
Upvotes: 1
Reputation: 1175
This will result to a string after using the ToString()
method and not a Datetime
var myBirthDate= BirthDate.ToString("yyyy-MM-dd HH':'mm':'ss");
Use DateTime.TryParse to get a DateTime from the value provided by your client. Then use it in your query.
Upvotes: 1