2017-09-26 32 views
1

使用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 enter image description here

視圖模型(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上發生。任何想法我錯了?

+0

你試過了嗎?CreatedDate = m.Field (「CreatedDate」)'?請注意'DateTime?'與'DateTime'不同。 –

+0

@TetsuyaYamamoto我*認爲*應該是好的,因爲你[允許](http://share.linqpad.net/f9445g.linq)設置'DateTime?'爲'DateTime'。 –

+0

「DataTable」上的所有字段是否與您試圖從字段中拉出的數據類型實際匹配?即。 'CreatedDate' *真的是'DateTime'而不是'字符串',看起來像是'DateTime'? –

回答

1

沒有足夠的creds評論 - 這樣:

切換到這個過載:DataColumnCollection.Add (String, Type)並指定類型明確

您使用的Add告訴我:

默認情況下,數據類型新的列是字符串。

這應該可以解決您的問題。

+0

謝謝!有效。感謝@Bradley Uffner。 – AdityaRao

相關問題