2016-10-02 86 views
0

我需要從使用ODATA的Web API服務器(C#)中查詢舊數據庫中的表。我有一個傳統數據庫的基本ODBC驅動程序,我只需要在這個時候支持基本的過濾(eq,startswith和substringof)。例如:

queryOptions.Filter.RawValue:

​​

應該被轉換爲這樣的事情(我只關心這裏的WHERE子句):

SELECT CustName, Address1, Address2, ... 
FROM Customers 
WHERE CustName like 'Bill%' AND 
    Address1 like '%sunset% AND 
    Phone like '%7421%' 

我意識到解析RawValue可能不是一個好主意。

有沒有人有類似的東西可以用來作爲起點?或建議一個好的,可靠的方式來實現這一目標?

+0

見我的回答在這個線程。 http://stackoverflow.com/a/36956462/3271357 – PvPlatten

+0

我也發佈了一個替代在http://stackoverflow.com/questions/28372999/translate-odata-queries-to-sql/42547175#42547175 –

回答

0

您將需要應用一些正則表達式到原始值,獲得匹配並應用一些邏輯來進行轉換。 基本上,使用參數搜索功能,刪除功能文本,獲取參數並將它們轉換爲類似的子句。 事情是這樣的:

string str = @"((startswith(Name,'Bill')) and 
(substringof('sunset',Address)) and 
(substringof('7421',Phone)))"; 

System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"startswith\(([^\)]+)\)"); 

System.Text.RegularExpressions.Match match = regex.Match(str); 

if (match.Success) 
{ 
    string tmp = match.Value; 
    string destination = "@field LIKE '@val%'"; 

    tmp = tmp.Replace("startswith(",""); 
    tmp = tmp.Replace(")",""); 

    string[] keyvalue = tmp.Split(','); 
    string field = keyvalue[0]; 
    string val = keyvalue[1]; 

    destination = destination.Replace("@field", field); 
    destination = destination.Replace("@val", val.Replace("'","")); 
    Console.WriteLine(destination); 
} 

此輸出:

Name LIKE 'Bill%' 
+0

@ epsino316謝謝,但使用reg ex解析原始值可能會有點脆弱(ODATA查詢過濾器基於用戶在UI中輸入的任何內容,包括除非轉義纔會中斷正則表達式的字符等)。我希望找到一個更強大的方法(無需編寫我自己的查詢提供程序)。 – Lars335

+0

想不到沒有它的東西。可能是一些商業轉換工具,或者在github中尋找一個開源特定項目。 – espino316