我称您声称该列存储为DateTime
. 我敢打赌,您实际上是在该列中存储日期的字符串表示形式。
为了演示,这里有一个简单的例子,你会得到什么异常(如果有的话)。
var dt = new DataTable();
dt.Columns.Add("AsString", typeof(string));
dt.Columns.Add("AsDateTime", typeof(DateTime));
var now = DateTime.Now;
var row = dt.Rows.Add(now.ToString(), now);
row.Field<string>("AsString"); // this is fine
row.Field<string>("AsDateTime"); // InvalidCastException: Unable to cast object of type 'System.DateTime' to type 'System.String'.
row.Field<DateTime>("AsString"); // InvalidCastException: Specified cast is not valid.
row.Field<DateTime>("AsDateTime"); // this is fine
DateTime.Parse(row.Field<string>("AsString")); // this is fine
因此,您应该能够看到,当您尝试读取存储为 a的字段string
但您尝试将其作为 a 访问时DateTime
,它会抛出您刚刚描述的消息的异常。
有两种方法可以解决它。
我建议更改列上的类型,使其适用于DateTime
对象并实际存储DateTime
值。不,字符串表示将不起作用。然后,您的查询将按照您的预期工作,无需额外更改。
否则,请更改您的查询,以便您使用正确的类型 (a string
) 访问该字段,将其解析回一个DateTime
对象并从那里开始。
var now = DateTime.Now;
var query =
from row in dt.AsEnumerable()
let startDate = DateTime.Parse(row.Field<string>("StartDate"))
where SqlMethods.DateDiffDay(
TimeZone.CurrentTimeZone.ToLocalTime(startDate),
now) >= 0
select row;