问题
I use WCF service with ORACLE and SQL Server. Then I need "generic" solution.
I need built a WCF method to essentially execute a custom SQL string and return the reader results.
This is not a great practice and is probably best avoided, it kind of breaks the whole point of the WCF service, but in my case this need have to be done.
I don't want neither cannot WCF Data Service neither another technology or protocol.
Only WCF service (SOAP).
Any good practices about it?
Maybe List<List<string>>
return value requires improvement.
Source code for SQL Server. The same for Oracle.
[OperationContract]
List<List<string>> executeSQL(string sql, bool returnExpected);
public List<List<string>> executeSQL(string sql, bool returnExpected)
{
List<List<string>> toReturn = new List<List<string>>();
using (SqlConnection con = new SqlConnection(YourConnectionString))
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = sql;
if (returnExpected == true)
{
using (SqlDataReader sqlReader = cmd.ExecuteReader())
{
if (sqlReader != null)
{
if (sqlReader.HasRows)
{
while (sqlReader.Read())
{
List<string> innerList = new List<string>();
for (int i = 0; i < sqlReader.FieldCount; i++)
{
innerList.Add(sqlReader[i].ToString());
}
toReturn.Add(innerList);
}
con.Close();
}
}
}
}
else
{
// We execute without reader
cmd.ExecuteNonQuery();
}
}
return toReturn;
}
回答1:
Define operation contract
[OperationContract]
string executeSQL(string sql, bool returnExpected);
converting list to json string
return Newtonsoft.Json.JsonConvert.SerializeObject(YourResultList);
parsing json string to object
var res = (YourClass)Newtonsoft.Json.JsonConvert.DeserializeObject(s, typeof(YourClass));
来源:https://stackoverflow.com/questions/26514844/executing-a-custom-sql-query-over-wcf