2012-04-30 117 views
0

我是Linq的新手,下面的查詢不斷返回「無法識別System.DateTime」錯誤。我試過解析和轉換,但都不起作用。這是我的查詢:LINQ to Entities無法識別方法'System.DateTime Parse(System.String)'方法

mrcEntities context = GetContext();

 var query = from c in context.tblClients 
        where (c.FirstName != null || c.LastName != null) 
         && c.EligibilityDate >= DateTime.Parse("10/01/2011") 
         && c.EligibilityDate <= DateTime.Parse("04/30/2012") 
         orderby c.ClientID 
        select new 
        { 
         ClientID = c.ClientID, 
         FirstName = c.FirstName, 
         LastName = c.LastName, 
         MiddleName = c.MidName, 
         SSN = c.SSN, 
         DOB = c.DOB, 
         Sex = c.Gender, 
         Ethnic = c.EthnicCode 
        }; 

     clientRowCnt = query.Count(); 

任何幫助,將不勝感激。

回答

4

這是因爲EF無法將DateTime.Parse轉換爲商店中可用的功能。如果將調用的結果替換爲DateTime.Parse()並在查詢中使用這些變量,它應該可以正常工作。

var from = DateTime.Parse("10/01/2011"); 
var to = DateTime.Parse("04/30/2012"); 
var query = from c in context.tblClients 
        where (c.FirstName != null || c.LastName != null) 
         && c.EligibilityDate >= from 
         && c.EligibilityDate <= to 
         orderby c.ClientID 
        select new 
        { 
         ClientID = c.ClientID, 
         FirstName = c.FirstName, 
         LastName = c.LastName, 
         MiddleName = c.MidName, 
         SSN = c.SSN, 
         DOB = c.DOB, 
         Sex = c.Gender, 
         Ethnic = c.EthnicCode 
        }; 

     clientRowCnt = query.Count(); 
2

只是解析查詢以外的日期。或者使用構造,甚至沒有分析它(你知道這些值已經似乎創建日期

DateTime start = DateTime.Parse("10/01/2011"); 
DateTime emd = DateTime.Parse(04/30/2012); 

var query = from c..... 

或使用:。

DateTime start = new DateTime(2011, 10, 01); 
DateTime end = new DateTime(2012, 04, 30); 

var query = from c..... 

您也可以安全地解析字符串中的突出部分您的查詢,因爲這部分數據後在客戶端執行已被檢索。因此

var query = from c... 
select 
    new { 
     EligibilityDate = Datetime.Parse(c.EligibilityDate) 
    } 

需要在選擇標準的分析價值時,它的唯一的,當您將n提供它作爲日期時間值。

到目前爲止,一個更好的解決方案是修復數據庫模式,甚至只是將計算列添加到在服務器上進行解析並公開正確的Typed列的現有模式。

+0

如果DateTime.Parse依賴於「from c」會怎麼樣?例如, DateTime.Parse(c.date)? –

+0

對不起,你能詳細說明一下嗎? 「不認識方法」會不會發生? –

+0

是的,謝謝你! –

相關問題