WCF Web Services + 連接 Database 使用方法 (SOAP Server Side / SOAP Client Side – Return DataSet)
(SOAP Server Side)
IService1.cs |
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.ServiceModel; using System.Data; namespace WcfService1 { // 注意: 您可以使用 [重構] 功能表上的 [重新命名] 命令同時變更程式碼和組態檔中的介面名稱 "IService1"。 [ServiceContract] public interface IService1 { [OperationContract] DataSet getPlayer(); // TODO: 在此新增您的服務作業 } } |
Service1.svc.cs |
using System; using System.Collections.Generic; using System.Text; using System.Data.SqlClient; using System.ServiceProcess; using System.Data; namespace WcfService1 { // 注意: 您可以使用 [重構] 功能表上的 [重新命名] 命令同時變更程式碼、svc 和組態檔中的類別名稱 "Service1"。 public class Service1 : IService1 { public DataSet getPlayer() { String connectionString1 = "Data Source=.\\SqlExpress; Initial Catalog=Soccer; Integrated Security=SSPI"; SqlConnection con1 = new SqlConnection(connectionString1); con1.Open(); StringBuilder sb = new StringBuilder(); sb.Append("SELECT * FROM dbo.Player;"); SqlDataAdapter Adapter = new SqlDataAdapter(sb.ToString(), con1); DataSet ds = new DataSet(); Adapter.Fill(ds); con1.Close(); con1.Dispose(); return ds; } } } |
(SOAP Client Side – 需自行增加 Service References)
Default.aspx |
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.ServiceModel; using System.Data; private void WebServiceGridView() { Service1Client WCFObj = new Service1Client(); DataSet ds = WCFObj.getPlayer(); DataTable dt = ds.Tables[0]; GridView1.DataSource = dt; GridView1.DataBind(); WCFObj.Close(); } |