2016-10-02 85 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