我如何在WCF模块C#中执行存储过程

时间:2019-02-04 11:37:14

标签: c# wcf

我正在创建一个wcf模块,我想执行一个存储过程并返回结果。这是我到目前为止所拥有的

public static class Provder
{

 private const string CommandSchema_FullName = "Table3";
    public static IEnumerable<ProviderModel> Get(Func<ProviderModel> )
    {
        var query = new StringBuilder();
        query.AppendFormat("SELECT * FROM {0}", CommandSchema_FullName);
        if (criteria != null)
            return ExecuteQuery(query.ToString()).Where(criteria).ToArray();
        return ExecuteQuery(query.ToString());  

//我可以从上面的表中读取,我不确定如何添加我想调用的新存储过程         }

    private static IEnumerable<ProviderModel> ExecuteQuery(string query)
    {
        var result = new List<ProviderModel>();
        using (var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["netTiersConnectionString"].ToString()))
        {
            sqlConnection.Open();
            var reader = new SqlCommand(query, sqlConnection).ExecuteReader();
            while (reader.Read())
            {
                result.Add(new ProviderModel
                {

                });
            }
            sqlConnection.Close();
        }
        return result;
    }
    private static bool ExecuteCommand(string command)
    {
        var result = false;
        using (var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["netTiersConnectionString"].ToString()))
        {
            sqlConnection.Open();
            try
            {
                var recordsAffected = new SqlCommand(command, sqlConnection).ExecuteNonQuery();
                result = true;
            }
            catch (SqlException)
            {
                result = false;
            }
            finally
            {
                sqlConnection.Close();
            }
        }
        return result;
    }
}
public class ProviderModel
{

}

这是我要在上述方法中调用的存储过程

 CREATE PROCEDURE GetListCodes 
AS
BEGIN
    select concat(p.CourseName,s.LeagueTitle,' ',p.Abbreviation) As Result,p.ProgramCode
  FROM Table1 p inner join Table2 s on p.Code=s.Code
END
GO

我不确定如何在上述wcf模型中调用sp GetListCodes。我没有任何要传递的参数,我只想执行存储过程并获取结果。

1 个答案:

答案 0 :(得分:0)

您需要执行存储过程,命令上只需一行

  

cmd.CommandType = CommandType.StoredProcedure;

在您的情况下,您必须替换行

  

var recordsAffected = new SqlCommand(command,   sqlConnection).ExecuteNonQuery();

var cmd= new SqlCommand(command, sqlConnection);
cmd.CommandType = CommandType.StoredProcedure;
var recordsAffected = cmd.ExecuteNonQuery();

有一个不错的小教程,您可以在https://csharp-station.com/Tutorial/AdoDotNet/Lesson07

中找到

Miscrosoft在https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/executing-a-command上也有一篇文章