使用Lambda通過DataTable對象進行解析時,我沒有看到以下代碼中出現了什麼問題。對於日期時間C#lambda解析「指定的轉換無效」
List<ApprovalPCNReportViewModel> report = GetApprovalPCNReport().AsEnumerable().Select(m => new ApprovalPCNReportViewModel()
{
PCNNotificationNumber = m.Field<String>("NotifiDocNumber"),
CreatedDate = m.Field<DateTime>("CreatedDate"),
EmailRecipients = m.Field<String>("EmailRecipients"),
EmailSentDate = m.Field<DateTime>("EmailSentDate"),
EmailOpenedDate = m.Field<DateTime>("EmailOpenedDate"),
MailFrequency = m.Field<int>("MailFrequency"),
ApprovedDate = m.Field<DateTime>("ApprovedDate"),
ApprovedBy = m.Field<String>("ApprovedBy")
}).ToList();
DataTable的結合 -
public DataTable GetApprovalPCNReport()
{
DataTable dt = new DataTable();
dt.Columns.Add("NotifiDocNumber");
dt.Columns.Add("CreatedDate");
dt.Columns.Add("EmailRecipients");
dt.Columns.Add("EmailSentDate");
dt.Columns.Add("EmailOpenedDate");
dt.Columns.Add("MailFrequency");
dt.Columns.Add("ApprovedDate");
dt.Columns.Add("ApprovedBy");
for (int i = 0; i < 100; i++)
{
DataRow dr = dt.NewRow();
dr["NotifiDocNumber"] = "Column1 - Row " + i;
dr["CreatedDate"] = DateTime.Now;
dr["EmailRecipients"] = "Column3 - Row " + i;
dr["EmailSentDate"] = DateTime.Now;
dr["EmailOpenedDate"] = DateTime.Now;
dr["MailFrequency"] = i;
dr["ApprovedDate"] = DateTime.Now;
dr["ApprovedBy"] = "Column6 - Row " + i;
dt.Rows.Add(dr);
}
return dt;
}
這裏是數據 - The DataTable values
視圖模型(ApprovalPCNReportViewModel) -
public String PCNNotificationNumber { get; set; }
public DateTime? CreatedDate { get; set; }
public String EmailRecipients { get; set; }
public DateTime EmailSentDate { get; set; }
public DateTime EmailOpenedDate { get; set; }
public Int32 MailFrequency { get; set; }
public DateTime ApprovedDate { get; set; }
public String ApprovedBy { get; set; }
我敢肯定無效的轉換異常正在DateTime和Int上發生。任何想法我錯了?
你試過了嗎?CreatedDate = m.Field(「CreatedDate」)'?請注意'DateTime?'與'DateTime'不同。 –
@TetsuyaYamamoto我*認爲*應該是好的,因爲你[允許](http://share.linqpad.net/f9445g.linq)設置'DateTime?'爲'DateTime'。 –
「DataTable」上的所有字段是否與您試圖從字段中拉出的數據類型實際匹配?即。 'CreatedDate' *真的是'DateTime'而不是'字符串',看起來像是'DateTime'? –