Executing a custom SQL query over WCF

筅森魡賤 提交于 2020-01-23 03:57:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!