如何使用c#通过Web服务调用存储过程?

时间:2009-09-29 03:58:30

标签: c# wcf web-services stored-procedures

我是网络服务的新手,

数据库访问应该通过Web服务使用ADO.NET来访问存储过程。

任何想法?

2 个答案:

答案 0 :(得分:15)

如果您重新开始,我强烈建议您开始使用WCF(而不是旧式的ASMX Web服务)。

在这种情况下,您需要:

1)服务合同(定义您的网络服务上的操作的界面):

[ServiceContract]
public interface IMyDataService
{
    [OperationContract]
    YourDataType GetData(int idValue);
}

2)数据合同,它将定义您的呼叫的数据结构(此处:返回类型YourDataType):

[DataContract]
public class YourDataType
{
    bool boolValue = true;
    string stringValue = "Hello ";

    [DataMember]
    public bool BoolValue
    {
        get { return boolValue; }
        set { boolValue = value; }
    }

    [DataMember]
    public string StringValue
    {
        get { return stringValue; }
        set { stringValue = value; }
    }
}

3)服务类,它将实际实现您的Web服务方法,并使用存储过程调用数据库 - 如下所示:

public class YourDataService : IMyDataService
{
    public YourDataType GetData(int idValue)
    {
        YourDataType result = new YourDataType();

        using(SqlConnection _con = new SqlConnection("server=(local);database=test;integrated security=SSPI;"))
        {
            using(SqlCommand _cmd = new SqlCommand("YourStoredProcName", _con))
            {
                _cmd.Parameters.AddWithValue("@ID", idValue);

                _cmd.Parameters.Add("@OutStringValue", SqlDbType.VarChar, 20)
                               .Direction = ParameterDirection.Output;
                _cmd.Parameters.Add("@OutBoolValue", SqlDbType.Bit)
                               .Direction = ParameterDirection.Output;

                _cmd.ExecuteNonQuery();

                result.StringValue = _cmd.Parameters["@OutStringValue"].Value.ToString();
                result.BoolValue = Convert.ToBoolean(_cmd.Parameters["@OutBoolValue"].Value);

            }
        }

        return result;
    }
}

在这里,请注意我完全假设您的存储过程看起来像(在我的情况下,类似于:

CREATE PROCEDURE dbo.YourStoredProcName
   (@ID INT, @OutStringValue VARCHAR(20) OUTPUT, @OutBoolValue BIT OUTPUT)

这对你来说可能完全不同!您需要确保根据实际情况进行调整!

4)最终,您需要一种方法来托管您的WCF服务(在IIS中,或者您自己在控制台应用程序或NT服务中) - 这只是标准的WCF工作

5)最后但同样重要的是,您的客户端应用程序需要向该WCF服务“添加服务引用”以便能够再次调用它:这是完全标准的WCF内容,此处不需要特殊步骤。 / p>

所以你有它 - 一个WCF服务在数据库中调用你的存储过程,将一些自定义数据类型的值返回给调用者。

马克

答案 1 :(得分:5)

请参阅The C# Station ADO.NET Tutorial - Lesson 07: Using Stored Procedures

  

本课程介绍如何使用存储   数据访问代码中的过程。   以下是此目标   课:

     
      
  • 了解如何修改SqlCommand对象以使用存储的   过程。
  •   
  • 了解如何在存储过程中使用参数。
  •