Anu*_*uya 1 c# wcf stored-procedures web-services
我是网络服务新手,
数据库访问应该通过Web服务使用ADO.NET来访问存储过程.
有任何想法吗 ?
mar*_*c_s 15
如果您重新开始,我强烈建议您开始使用WCF(而不是旧式的ASMX Web服务).
在这种情况下,您需要:
1)服务合同(定义Web服务上的操作的接口):
[ServiceContract]
public interface IMyDataService
{
[OperationContract]
YourDataType GetData(int idValue);
}
Run Code Online (Sandbox Code Playgroud)
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; }
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,请注意我完全假设您的存储过程看起来像(在我的情况下,类似于:
CREATE PROCEDURE dbo.YourStoredProcName
(@ID INT, @OutStringValue VARCHAR(20) OUTPUT, @OutBoolValue BIT OUTPUT)
Run Code Online (Sandbox Code Playgroud)
这对你来说可能完全不同!您需要确保根据您的实际情况进行调整!
4)最终,您需要一种方法来托管您的WCF服务(在IIS中,或者您自己在控制台应用程序或NT服务中) - 这只是标准的WCF工作
5)最后但并非最不重要的是,您的客户端应用程序将需要"添加服务引用"到该WCF服务以便能够再次调用它:这是完全标准的WCF内容,此处不需要特殊步骤.
所以你有它 - 一个WCF服务在数据库中调用你的存储过程,将一些自定义数据类型的值返回给调用者.
渣
请参阅C#Station ADO.NET教程 - 第07课:使用存储过程:
本课程介绍如何在数据访问代码中使用存储过程.以下是本课的目标:
- 了解如何修改SqlCommand对象以使用存储过程.
- 了解如何将参数与存储过程一起使用.
| 归档时间: |
|
| 查看次数: |
27034 次 |
| 最近记录: |