2011-11-26 81 views
2

我有例外:空值不能被分配到一個成員類型的System.DateTime

The null value cannot be assigned to a member with type System.DateTime which is a non-nullable value type. 
Source Error: 
var bd = (from d in baza.hpurs where d.userID == userID && d.date !=null select d.date).Max(); 

我的方法:

public ActionResult Add_hours(int userID) 
    { 
     var dat = DateTime.Today; 

     var bd = (from d in baza.hours where d.userID == userID && d.date !=null select d.date).Max(); 

     if (bd != dat) 
     { 
      return View(); 
     } 

    else 
    { 
     var dd = (from d in baza.hours where d.userID == userID && d.date == dat select d.hoursID).Single(); 
     return RedirectToAction("hours_is", "Employer", new { HoursID = dd }); 
    } 
} 

它的工作原理很好,但只有當我有1個或多個以小時表格爲具體用戶的數據。 這個錯誤是當我想添加幾小時到具體用戶沒有添加任何小時的表格。 我沒有任何想法如何修復它...

回答

7

這是LINQ to SQL是漏洞抽象的一點。如果在序列中沒有元素,C#中Max()函數的語義是拋出InvalidOperationException。 SQL的MAX()函數的語義是返回NULL。 C#代碼編譯好像遵循C#語義,但代碼從未作爲C#代碼執行。它被轉換爲SQL語義規則所在的SQL。

要處理此問題,您需要在沒有匹配元素時決定想要的內容。如果你想要一個null值,顯式聲明一個可爲空的變量並引入一個額外的轉換到DateTime?告訴LINQ to SQL可能返回null

DateTime? bd = (from d in baza.hpurs 
       where d.userID == userID && d.date !=null 
       select (DateTime?)d.date).Max(); 
+0

非常感謝。是工作。 – user1031034

+0

非常感謝你 –

+0

感謝您的解釋,讓我有點瘋狂,試圖找到愚蠢的解決方法。 – Yablargo

-1

問題很可能在:d.date!= null ...因爲日期不能爲空。另一種選擇是使其可以爲空(使用'?'類型的後綴)或使用類似DateTime.MinValue的東西。

相關問題