天天看點

30.Silverlight中建立一個最簡單的WCF RIA Services通路資料庫執行個體

 本文将建立一個最簡單的WCF RIA Services通路資料庫的執行個體,附帶有資料庫檔案,可以在Sql Server中附加資料庫,在本文中并沒有采用ADO.NET實體資料模型綁定資料庫,而是單獨寫一個類來連接配接資料庫查詢資料表并傳回值,下面我們看詳細 步驟。

        第一步:首先我們打開VS2010,建立一個Silverlight應用程式項目SLGetDataFromWCFRIA。

<a target="_blank" href="http://blog.51cto.com/attachment/201203/180855499.jpg"></a>

        第二步:點選确定之後,在彈出的“建立Silverlight應用程式”視窗中,選中“啟用 WCF RIA 服務”複選框然後确定。

<a target="_blank" href="http://blog.51cto.com/attachment/201203/180915404.jpg"></a>

        第三步:在建立好的項目中,滑鼠右鍵點選“SLGetDataFromWCFRIA.Web”項目,然後“添加”--&gt;“建立項”--&gt;“WCF服務”,命名為SLWCFRIA.svc。

<a target="_blank" href="http://blog.51cto.com/attachment/201203/180934741.jpg"></a>

        第四步:在上一步生成的ISLWCFRIA.cs檔案中,我們可以定義相關的通信的契約,在本執行個體中我們定義一個string GetData()契約。

<a target="_blank" href="http://blog.51cto.com/attachment/201203/180955408.jpg"></a>

        第五步:在SLWCFRIA.svc.cs檔案中我們實作這個契約函數,代碼如下:

using System; 

using System.Collections.Generic; 

using System.Linq; 

using System.Runtime.Serialization; 

using System.ServiceModel; 

using System.Text; 

using System.Data; 

using System.Data.SqlClient; 

namespace SLGetDataFromWCFRIA.Web 

// 注意: 使用“重構”菜單上的“重命名”指令,可以同時更改代碼、svc 和配置檔案中的類名“SLWCFRIA”。 

public class SLWCFRIA : ISLWCFRIA 

public void DoWork() 

public string GetData() 

DataSet ds= DB.Getdata("select * from userinfo"); 

return ds.GetXml(); 

        第七步:我們在SQL SERVER2008中建立一個示例資料庫名為SLRiaTest。在這個資料庫裡面新增一個UserInfo表,在裡面添加字段如下:

<a target="_blank" href="http://blog.51cto.com/attachment/201203/181043729.jpg"></a>

        第八步:編寫一個類,來連接配接SLRiaTest資料庫,擷取DataSet資料集。

DB.cs資料庫通路類

/// &lt;summary&gt; 

   /// DB 的摘要說明 

   /// &lt;/summary&gt; 

   public   class  DB 

   { 

       private static IsolationLevel m_isoLevel = IsolationLevel.ReadUncommitted; 

       private static string connStr = string.Empty; 

       private DB() 

       { 

       } 

       #region DB2 Access Functions 

       static public IsolationLevel IsolationLevel 

           get 

           { 

               return m_isoLevel; 

           } 

       /// &lt;summary&gt; 

       /// Gets Connection out of Web.config 

       /// &lt;/summary&gt; 

       /// &lt;returns&gt;Returns SqlConnection&lt;/returns&gt; 

       public static SqlConnection GetConnection() 

           if (connStr == string.Empty) 

               AppSettingsReader configurationAppSettings = new AppSettingsReader(); 

               connStr = "Data Source=CXL-DC6F5F6CA80;POOLING=FALSE;database=SLRiaTest;User ID=sa;Password=123456"; 

           SqlConnection conn = new SqlConnection(connStr); 

           conn.Open(); 

           return conn; 

       /// Gets data out of database using a plain text string command 

       /// &lt;param name="sql"&gt;string command to be executed&lt;/param&gt; 

       /// &lt;returns&gt;DataTable with results&lt;/returns&gt; 

       static public DataSet Getdata(string sql) 

           using (SqlConnection conn = GetConnection()) 

               using (SqlTransaction trans = conn.BeginTransaction(m_isoLevel)) 

               { 

                   try 

                   { 

                       using (SqlCommand cmd = conn.CreateCommand()) 

                       { 

                           if (sql != null) 

                           { 

                               sql = sql.ToLower().Replace("&lt;;", "");//.Replace(Convert.ToChar(32).ToString(), "&amp;nbsp;").Replace(" ", "&amp;nbsp;").Replace("%32", "&amp;nbsp;").Replace("%20", "&amp;nbsp;"); 

                               sql = sql.Replace("&gt;;", ""); 

                               sql = sql.Replace("script", ""); 

                               sql = sql.Replace("object", ""); 

                               sql = sql.Replace("applet", ""); 

                               sql = sql.Replace("[", ""); 

                               sql = sql.Replace("]", ""); 

                               sql = sql.Replace("execute", ""); 

                               sql = sql.Replace("exec", ""); 

                               sql = sql.Replace("union", ""); 

                               sql = sql.Replace("drop", ""); 

                               sql = sql.Replace("delete", ""); 

                               //  sql = sql.Replace("chr", ""); 

                               //sql = sql.Replace("mid", ""); 

                               sql = sql.Replace("truncate", ""); 

                               sql = sql.Replace("nchar", ""); 

                               //  sql = sql.Replace("varchar", ""); 

                               //sql = sql.Replace("char", ""); 

                               sql = sql.Replace("alter", ""); 

                               // sql = sql.Replace("cast", ""); 

                               sql = sql.Replace("exists", ""); 

                               sql = sql.Replace("update", ""); 

                           } 

                           cmd.Transaction = trans; 

                           cmd.CommandType = CommandType.Text; 

                           cmd.CommandText = sql; 

                           using (DataSet ds = new DataSet()) 

                               using (SqlDataAdapter da = new SqlDataAdapter()) 

                               { 

                                   da.SelectCommand = cmd; 

                                   da.SelectCommand.Connection = conn; 

                                   da.Fill(ds); 

                                   return ds; 

                               } 

                       } 

                   } 

                   finally 

                       trans.Commit(); 

               } 

       #endregion 

   } 

        第九步:滑鼠右鍵點選SLGetDataFromWCFRIA項目“添加服務引用”即引用剛才我們編寫的WCF服務。

<a target="_blank" href="http://blog.51cto.com/attachment/201203/181146919.jpg"></a>

        第十步:添加一個UserInfo的實體類集合。代碼如下:

    /// 使用者實體類 

    /// &lt;/summary&gt; 

    public class UserInfo 

    { 

        private string _ID; 

        private string _UserName; 

        private string _UserAddr; 

        private string _UserTel; 

        public string ID 

        { 

            get { return _ID; } 

            set { _ID = value; } 

        } 

        public string UserName 

            get { return _UserName; } 

            set { _UserName = value; } 

        public string UserAddr 

            get { return _UserAddr; } 

            set { _UserAddr = value; } 

        public string UserTel 

            get { return _UserTel; } 

            set { _UserTel = value; } 

    } 

        第十一步:點選MainPage.xaml檔案,添加一個DataGird控件命名為grShow,在MainPage.xaml.cs檔案中編寫以下代碼擷取WCF RIA services讀取到的資料庫資料:

public partial class MainPage : UserControl 

  { 

      public MainPage() 

      { 

          InitializeComponent(); 

          //建立一個代理類的執行個體 

          SLWCFRIAClient client = new SLWCFRIAClient(); 

          //調用GetData方法并加載事件 

          client.GetDataAsync(); 

          client.GetDataCompleted += new EventHandler&lt;GetDataCompletedEventArgs&gt;(client_GetDataCompleted); 

      } 

      public  List&lt;UserInfo&gt; userList = new List&lt;UserInfo&gt;(); 

      void client_GetDataCompleted(object sender, GetDataCompletedEventArgs e) 

          using (XmlReader xReader = XmlReader.Create(new StringReader(e.Result))) 

          { 

              //XmlReader讀取XML資料 

              while (xReader.ReadToFollowing("Table")) 

              { 

                  xReader.ReadToDescendant("ID"); 

                  string id = xReader.ReadElementContentAsString(); 

                  xReader.ReadToNextSibling("UserName"); 

                  string username = xReader.ReadElementContentAsString(); 

                  xReader.ReadToNextSibling("UserAddr"); 

                  string useraddr = xReader.ReadElementContentAsString(); 

                  xReader.ReadToNextSibling("UserTel"); 

                  string usertel = xReader.ReadElementContentAsString(); 

                  //執行個體化類并添加進實體類List&lt;&gt; 

                  UserInfo uinfo = new UserInfo(){ID=id, UserName=username,UserAddr=useraddr,UserTel=usertel}; 

                  userList.Add(uinfo); 

              } 

              this.grShow.ItemsSource = userList; 

          } 

  } 

<a target="_blank" href="http://blog.51cto.com/attachment/201203/181248528.jpg"></a>

本文轉自程興亮 51CTO部落格,原文連結:http://blog.51cto.com/chengxingliang/822557