2016-09-29 49 views
2

我有LINQ查詢與可空的數據時間字段,根據條件填充值。Linq中可空的日期時間字段的情況說明

var result=(from t1 in context.table1 
      join t2 in context.table2 
      on t1.id equals t2.fieldId 
      select new model1 
      { 
       name= t2.name, 
       DateCompleted = t1.Status == "Success" 
        ? Convert.ToDateTime(t1.CompletedDate) 
        : Null 
      }).ToList(); 

這裏DateCompleted可爲空的。如果狀態良好的話,只有我需要完成date.Other明智的,我需要表現出來空。現在「:Null」部分拋出錯誤。

在此先感謝 李蘇濱

+0

嘗試使用空值代替NULL –

+0

重複的htt p://stackoverflow.com/questions/16769233/how-to-set-datetime-to-null –

回答

4

試試這個

var result=(from t1 in context.table1 
      join t2 in context.table2 
      on t1.id equals t2.fieldId 
      select new model1 
      { 
      name= t2.name, 
      DateCompleted = t1.Status == "Success" ? Convert.ToDateTime(t1.CompletedDate): (DateTime?)null 
                  }).ToList(); 
+0

你比我快:+1 :) – user449689

+0

這就是所有關於upvote畢竟。 –

3

試試下面的代碼:

var result=(from t1 in context.table1 
      join t2 in context.table2 
      on t1.id equals t2.fieldId 
      select new model1 
      { 
       name= t2.name, 
       DateCompleted = t1.Status == "Success" 
        ? Convert.ToDateTime(t1.CompletedDate) 
        : (DateTime?) null 
      }).ToList(); 
1

您需要使用爲空的日期時間:(?DATETIME)缺省