2013-10-08 28 views
-1

我試圖在腳手架索引視圖上運行一個非常簡單的搜索。通常這適用於我,但使用日期我無法使它工作。日期搜索轉換問題

在我的控制器中的代碼是:

public ActionResult Index(DateTime SearchDate) 
{ 
    var query = from a in db.AppointmentProcedures 
       where a.BookingStatus == false 
       orderby a.AppointmentStartTime 
       select a; 

    if (SearchDate != null) 
    { 

     query = from a in db.AppointmentProcedures 
        orderby a.AppointmentDate 
        where a.AppointmentDate == SearchDate 
        select a; 
    } 

    return View(query); 
} 

但是我得到的轉換問題。在視圖中,我只有一個簡單的日期時間選擇器。

+3

什麼是**實際錯誤?** –

+0

DateTime不能爲空。可能發生的是SearchDate == DateTime.MinValue,並且該值沒有SQL DateTime表示。 – drch

+0

@drch這是有道理的,假設一個日期時間總是回來,那麼當天查詢日期的方式是什麼(因爲我認爲==會假設時間) – NickP

回答

1

DateTime是一個結構體,不能爲空。如果MVC無法綁定它,它將使用default(DateTime),它等於DateTime.MinValue

DateTime.MinValue是0001年1月1日,但Sql DateTime的最小值是1753年1月1日。如果試圖在查詢中使用DateTime.MinValue,它會給你一個錯誤。

要解決此問題,您可以使用Nullable DateTime。代碼中的更改如下所示:

public ActionResult Index(DateTime? SearchDate) 
{ 
    var query = ...; 

    if (SearchDate != null) 
    { 
     query = ...; 
    } 

    return View(query); 
} 
1

您的AppointmentDate類型是日期嗎?

如果是的話,就沒有必要轉換SearchDatestring

+0

對不起,AppointmentDate是一個日期時間。在發佈之前,我忘了更改該代碼。請參閱更新的解決方案 – NickP

+0

這就是我不幸遇到錯誤的地方。 – NickP

+0

請告訴我們實際的錯誤 –

0
  1. 這是很奇怪的,你存儲日期爲數據庫

  2. 串像以前一樣做一個轉換:

 
var converted = Convert.ToString(SearchDate); 
query = from a in db.AppointmentProcedures 
orderby a.AppointmentDate 
where a.AppointmentDate == converted 
select a;

因爲它不會識別Convert.ToString()函數(將嘗試解釋爲SQL函數)。

1

如果它可以null。換句話說,用戶沒有指定值控制允許null。然後,你希望你的參數看起來像這樣:

DateTime? SearchDate 

,可以讓你做到這一點:

if (SearchDate.HasValue) 

,並進一步查詢改成這樣:

query = from a in db.AppointmentProcedures 
     orderby a.AppointmentDate 
     where a.AppointmentDate == SearchDate.Value 
     select a; 

如果不能null。然後是,檢查MinValue

if (SearchDate != DateTime.MinValue)