Linq查询 - 将查询结果转换为datetime [英] Linq query - convert query result to datetime
问题描述
在我的第一个查询(stringdQuery)中,我试图传递一个字符串日期。
In my first query (stringdQuery) I am trying to pass a string date.
var stringQuery = (from p in db.Database_CRE_Events
select new Loan()
{
cDate = p.LastUpdated
}).FirstOrDefault();
然后我想将第一个查询的字符串日期转换为datetime。这是因为,我将在我的第二个查询(dateQuery)中使用此日期,where子句只接受datetime类型字段。
Then I would like to convert string date from the first query into datetime. This is because, I would use this date in my second query (dateQuery) in where clause which only accepts datetime type field.
if (stringdQuery != null && stringdQuery.cDate.HasValue)
{
dtt = Convert.ToDateTime(stringdQuery);
}
var dateQuery = (from p in db.Database_CRE_Events.Where(c => c.LastUpdated == dtt)
select new Loan()
{
latest = p.Date
}).FirstOrDefault();
当我执行此功能时,在客户端,我被抛出错误 - 无法将STW_V1.Controllers.Loan类型的对象强制转换为System.IConvertible
以下行出错:
When I execute this function and on the client-side, I get thrown error – Unable to cast object of type 'STW_V1.Controllers.Loan' to type 'System.IConvertible
Error on the following line:
dtt = Convert.ToDateTime(stringQuery);
我在代码中遗漏了什么?
提前道歉,如果上述说明不明确,请随时提出进一步的问题。
谢谢
Am I missing something in the code?
Apology in advance, if the above explanation is not clear but please feel free to ask any further questions.
Thank you
推荐答案
有两个问题:
1:stringdQuery
的类型为贷款
。所以你试图将Loan-object转换为DateTime。但首先不需要转换 - 只需通过其.Value属性访问stringdQuery.cDate的DateTime值:
There are two problems:
1:stringdQuery
is of typeLoan
. So you're trying to convert a Loan-object to DateTime. But conversion isn't neccessary in the first place - just access the DateTime-value of stringdQuery.cDate by its .Value-property:
dtt = stringdQuery.cDate.Value;
2:我不知道你的意图是什么,但你的两个问题对我来说没什么意义:您正在查询第一个 Database_CRE_Event
,获取其 LastUpdated
-date,然后查询其LastUpdated-的第一个Database_CRE_Event-日期等于前者。这与第一个查询相同。你也可以先选择 Date
-property。
2: I don't know what your intention is here but your two queries don't make much sense to me: You're querying for the first Database_CRE_Event
, get its LastUpdated
-date and then query for the first Database_CRE_Event whose LastUpdated-date is equal to the former. Which will be the same as from the first query. You could as well select the Date
-property in the first place.
这篇关于Linq查询 - 将查询结果转换为datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!