问题描述
当我尝试执行以下查询时,我在Linq中出现指定的转换无效"错误消息.
I have "Specified cast is not valid" error message in Linq when i am trying to execute the below query.
var query = from a in dt.AsEnumerable()
where SqlMethods.DateDiffDay(TimeZone.CurrentTimeZone.ToLocalTime(a.Field<DateTime>("StartDate")), DateTime.Now) >= 0
select a;
我将StartDate设置为"1997-10-01T00:00:00".谁能帮我解决这个问题.
I have StartDate as '1997-10-01T00:00:00'. Can anyone help me to resolve this.
推荐答案
在您声称该列以DateTime
存储方式的声明中,我称呼恶作剧.我敢打赌,您实际上是在该列中存储日期的字符串表示形式.
I call shenanigans on your claim that the column is stored as a DateTime
. I bet you're actually storing a string representation of a date in that column.
为了演示,这是一个简单的示例,其中包含您将获得的异常(如果有).
To demonstrate, here's a simple example with what exceptions you would get (if any).
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
如您所见,尝试读取以string
形式存储在中的字段,但尝试以DateTime
形式访问它时,它会抛出异常您刚刚描述的消息.
So as you should be able to see, when attempting to read the field that is stored as a string
but you try to access it as a DateTime
, it throws the exception with the message you just described.
有两种解决方法.
我建议您更改列的类型,以便用于DateTime
对象,并实际存储DateTime
值.不,字符串表示形式将不起作用.然后,您的查询将按您期望的那样工作,而无需进行其他更改.
What I would recommend is to change the type on your column so it is for DateTime
objects and actually store DateTime
values. No, a string representation will not work. Then your query would work as you would expect it with no additional changes.
否则,请更改查询,以便您使用正确的类型(a string
)访问该字段,将其解析回DateTime
对象并从那里去.
Otherwise, change your query so you're accessing the field using the correct type (a string
), parse it back to a DateTime
object and go from there.
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;
这篇关于指定的演员表无效. Linq DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!