2014-11-06 39 views
0

的操作数,我使用LINQ查询,但得到错误 Cannot apply operator >= to operands of type system.datetime and string得到错误不能申请运营商类型的System.DateTime和字符串

这里是我的LINQ查询

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); 

我转换日期到yyyy-MM-dd HH':'mm':'ss格式因为我从客户端获得其他格式。

我该如何避免此错误?

+1

异常消息是自我描述性的! – 2014-11-06 10:09:51

回答

1

这将导致一个字符串使用ToString()方法之后,而不是一个日期时间

var myBirthDate= BirthDate.ToString("yyyy-MM-dd HH':'mm':'ss"); 

使用DateTime.TryParse获得由客户提供的价值日期时间。然后在你的查询中使用它。

1

如果您收到的日期与当前文化不同,您可以使用DateTime.Parse转换为正确的DateTime变量。

由于您正在使用ToString将DateTime类型转换为格式化的日期字符串,因此myBirthDate变量将成为String,因此> =将无法按预期工作。

下面是一个示例:

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); 
     }        
    } 
} 
+0

不知道我怎么能适合你的答案,根据我的问题。你能再次检查你的答案吗? – Happy 2014-11-06 10:20:50

+0

你的问题很清楚。该行var myBirthDate = BirthDate.ToString(“yyyy-MM-dd HH':​​'mm':'ss”);生成一个字符串变量,因此你不能使用> =来比较它。您需要将其转换为DateTime类型才能比较日期。 – 2014-11-06 10:22:57