2017-11-11 150 views
1

我創建像比較兩個字符串一個簡單的搜索:我怎麼能比較和SEACH字符串和日期時間C#

articles = _service.ArticleRepository.GetAll(id, new Expression<Func<Article, bool>>[] { x => x.Title.Contains(searchWord) }, a => a.ArticleCategory); 

和工程罰款;但我想在日期時間(日期)搜索,我寫不同的代碼:

articles = _service.ArticleRepository.GetAll(id, new Expression<Func<Article, bool>>[] { x => x.InsertDate ==DateTime.Parse(searchWord) }, a => a.ArticleCategory); 

articles = _service.ArticleRepository.GetAll(id, new Expression<Func<Article, bool>>[] { x => x.InsertDate.ToString("yyyyMMdd").Contains(searchWord) }, a => a.ArticleCategory); 

給我一個錯誤:

LINQ to Entities does not recognize the method 'System.DateTime Parse(System.String)' method, and this method cannot be translated into a store expression.

From this line int count = _db.Count();

我怎麼可以做一些字符串之間的比較和日期作爲一個字符串輸入日期(以不同的格式,如:2017/8/5或05/05/2017或2017-8-5或...)或甚至輸入一個數字(搜索所有日期有一個數字)?

回答

2

當LINQ查詢被執行,它會得到轉換成等價的SQL語句。 DateTime.Parse是將字符串轉換爲相應的DateTime的C#方法。沒有相應的SQL等價物可以這樣做。

您需要在LINQ查詢之前創建一個DateTime對象並使用它。

var d = DateTime.Parse(searchWord); 
var result= someEntityCollection.Where(a =>a.CreatedTime==d)); 

如果CreatedTimeDateTime字段,則比較將包括時間戳以及。也就是說,它不會簡單地給記錄該日期,但日期和具體時間部分

如果你想過濾特定日期的記錄(沒有時間),你可以使用DbFunctions.TruncateTime helper方法這樣做

var d = DateTime.Parse(searchWord); 
var result= someEntityCollection.Where(a => 
      DbFunctions.TruncateTime(a.CreatedTime)== DbFunctions.TruncateTime(d.Date)) 

DbFunctions.TruncateTime助手方法內System.Data.Entity命名空間中定義。所以確保你有一個使用聲明來使用它。

using System.Data.Entity; 

而且它是安全的使用DateTime.ParseExactTryParseExact的格式,比採用DateTime.Parse

var d = DateTime.ParseExact(searchWord, "dd/MM/yyyy", CultureInfo.InvariantCulture); 
1

你需要做你的查詢外的轉換:

var date=DateTime.Parse(searchWord); 
articles = _service.ArticleRepository.GetAll(id, new Expression<Func<Article, bool>>[] { x => x.InsertDate ==date }, a => a.ArticleCategory);