2009-08-20 172 views
0

我有以下問題:在數據庫表中記錄了Sales。其中一個字段是SaleDate,它是SQL Server日期類型。該網站現在允許在這個領域進行搜索。它允許僅搜索一年。使用Linq-to-SQL查詢日期

我們假設有一個記錄日期爲2008/11/01。如果我搜索「2008」,則返回條目,這當然是正確的。但搜索「2008/11/01」不會返回條目。

因此,這裏是我的代碼:

filteredSales = filteredSales.Where(s => s.SaleDate.ToString().Contains(searchterm)); 

I have also tried this ones: 
filteredSales = filteredSales.Where(s => s.SaleDate.Value.ToString().Contains(searchterm)); 
filteredSales = filteredSales.Where(s => s.SaleDate.Value.ToShortDateString().Contains(searchterm)); 

他們也不起作用。

也許這不是一個LinQ問題,但更多的文化,因爲這是一個德國的應用程序和搜索詞真的是「01.11.2008」。但是,當我輸出數據庫中的值,甚至直接查看數據庫中顯示的「01.11.2008」。

感謝您的幫助。

邁克爾

下面是基於以下選擇的答案的完整的解決方案:

try 
{ 
    DateTime sdt = DateTime.Parse(suchbegriff, new System.Globalization.CultureInfo("de-DE")); 
    filteredSales = filteredSales.Where(s => s.SaleDate.Value == sdt); 
} 
catch (FormatException e) 
{ 
    // in case we have only the year try to make a string match 
    filteredSales = filteredSales.Where(s => s.SaleDate.Value.Year.ToString().Equals(suchbegriff)); 
} 

邁克爾

回答

1

使用DateTime對象,不與例如字符串作出比較:

// Parse the search term string to DateTime, using the german culture 
DateTime date = DateTime.Parse(searchTerm, new CultureInfo("de-DE")); 

var sales = filteredSales.Where(s => s.SaleDate == date); 
1

您是否嘗試過類似

S => s.SalesDate ==日期.Parse(「2008年11月1日」)

S => s.SalesDate == Date.Parse(數值指明MyDate)

S => s.SalesDate.Year == 「2008」

以上是未經測試。特別是最後一個,但基本上你想要再次測試一年或者一年。

我不認爲我會在包含日期字段的查詢中使用包含。