2013-12-23 46 views
0

我想調用下面的查詢字符串,但我在客戶端收到'無數據'消息 - 'api/data?id = 786,899 & price_type = cvr'。如何在linq查詢中使用split?

public HttpResponseMessage Get([FromUri] Query query) 
{ 
    var data = db.database_ICs.AsQueryable(); 

    if (query.id!= null) 
    { 
     data = data.Where(c => query.id.Split(',').Contains(c.ID)); 
    } 
    if (query.price_type != null) 
    { 
     data = data.Where(c => c.Cover == query.price_type); 
    } 

    if (!data.Any()) 
    { 
     var message = string.Format("No data was found"); 
     return Request.CreateErrorResponse(HttpStatusCode.NotFound, message); 
    } 

    return Request.CreateResponse(HttpStatusCode.OK, data); 
} 

public class Query 
{ 
    public string id{ get; set; } 
    public string price_type { get; set; } 
    public Nullable<DateTime> startDate { get; set; } 
    public Nullable<DateTime> endDate{ get; set; } 
} 

任何幫助將非常感激。 非常感謝。

+0

是'c.ID'類型的字符串? – okrumnow

+0

這是'LINQ to SQL'嗎? 「LINQ to SQL」沒有將'string.Split'轉換爲SQL。 –

+0

hi @okrumnow,是的,這是正確的。 – user3070072

回答

0
var data = db.database_ICs.AsQueryable(); 
    if (!string.IsNullOrEmpty(query.id)) 
     { 
      var ids = query.id.Split(',').ToList(); 
      data = data.Where(c => ids.Contains(c.ID)); 
     } 

假設c.ID和ids元素是相同類型的課程。 編輯:檢查你是否有查詢字符串的一種方法

+0

什麼問題將其轉換爲列表求解? – EkoostikMartin

+0

它應該創建一個IN sql查詢,而不是嘗試在一組值中創建一個.sql –

+0

@ AD.Net,非常感謝您的幫助。當我單獨搜索'price-type'參數(api/data?price-type = cvr)時,它會拋出一個空異常錯誤 - ExceptionMessage「:」對象引用未設置爲對象實例。「, 「ExceptionType」:「System.NullReferenceException」,「StackTrace」:「,在以下代碼行(var ids ...)上。 – user3070072