详解Silverlight与Access互操作的具体实现


Silverlight与Access互操作是一个很基础的问题,主要涉及到数据库的操作。Access属于轻量级的数据库,应用起来还是比较方便的。51CTO编辑推荐《走向银光 —— 一步一步学Silverlight》

在开发一些小型应用程序时,我们就需要使用一些小巧的轻量级的数据库,比如Access数据库。由于Visual Studio中并没有直接提供Silverlight与Access互操作的系列方法。于是本文就将为大家介绍如何让Silverlight使用Access作为后台数据库。

准备工作

1)建立起测试项目

细节详情请见强大的DataGrid组件[2]_数据交互之ADO.NET Entity Framework——Silverlight学习笔记[10]。

2)创建测试用数据库

如下图所示,创建一个名为Employees.mdb的Access数据库,建立数据表名称为Employee。将该数据库置于作为服务端的项目文件夹下的App_Data文件夹中,便于操作管理。


建立数据模型

EmployeeModel.cs文件(放置在服务端项目文件夹下)

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. namespace datagridnaccessdb  
  5. {  
  6.     public class EmployeeModel  
  7.     {  
  8.         public int EmployeeID { get; set; }  
  9.         public string EmployeeName { get; set; }  
  10.         public int EmployeeAge { get; set; }  
  11.     }  

建立服务端Web Service★

右击服务端项目文件夹,选择Add->New Item....,按下图所示建立一个名为EmployeesInfoWebService.asmx的Web Service,作为Silverlight与Access数据库互操作的桥梁。

创建完毕后,双击EmployeesInfoWebService.asmx打开该文件。将里面的内容修改如下:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Services;  
  6. using System.Data.OleDb;//引入该命名空间为了操作Access数据库  
  7. using System.Data;  
  8. namespace datagridnaccessdb  
  9. {  
  10.     /// <summary> 
  11.     /// Summary description for EmployeesInfoWebService  
  12.     /// </summary> 
  13.     [WebService(Namespace = "http://tempuri.org/")]  
  14.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  15.     [System.ComponentModel.ToolboxItem(false)]  
  16.     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.   
  17.     // [System.Web.Script.Services.ScriptService]  
  18.     public class EmployeesInfoWebService : System.Web.Services.WebService  
  19.     {  
  20.         [WebMethod]//获取雇员信息  
  21.         public List<EmployeeModel> GetEmployeesInfo()  
  22.         {  
  23.             List<EmployeeModel> returnedValue = new List<EmployeeModel>();  
  24.             OleDbCommand Cmd = new OleDbCommand();  
  25.             SQLExcute("SELECT * FROM Employee", Cmd);  
  26.             OleDbDataAdapter EmployeeAdapter = new OleDbDataAdapter();  
  27.             EmployeeAdapter.SelectCommand = Cmd;  
  28.             DataSet EmployeeDataSet = new DataSet();  
  29.             EmployeeAdapter.Fill(EmployeeDataSet);  
  30.             foreach (DataRow dr in EmployeeDataSet.Tables[0].Rows)  
  31.             {  
  32.                 EmployeeModel tmp = new EmployeeModel();  
  33.                 tmp.EmployeeID = Convert.ToInt32(dr[0]);  
  34.                 tmp.EmployeeName = Convert.ToString(dr[1]);  
  35.                 tmp.EmployeeAge = Convert.ToInt32(dr[2]);  
  36.                 returnedValue.Add(tmp);  
  37.             }  
  38.             return returnedValue;  
  39.         }  
  40.        [WebMethod] //添加雇员信息  
  41.         public void Insert(List<EmployeeModel> employee)  
  42.         {  
  43.             employee.ForEach( x =>   
  44.            {  
  45.                 string CmdText = "INSERT INTO Employee(EmployeeName,EmployeeAge) VALUES('"+x.EmployeeName+"',"+x.EmployeeAge.ToString()+")";  
  46.                 SQLExcute(CmdText);  
  47.             });  
  48.         }  
  49.         [WebMethod] //更新雇员信息  
  50.        public void Update(List<EmployeeModel> employee)  
  51.         {  
  52.            employee.ForEach(x => 
  53.             {  
  54.                 string CmdText = "UPDATE Employee SET EmployeeName='"+x.EmployeeName+"',EmployeeAge="+x.EmployeeAge.ToString();  
  55.                 CmdText += " WHERE EmployeeID="+x.EmployeeID.ToString();  
  56.                 SQLExcute(CmdText);  
  57.             });  
  58.         }  
  59.         [WebMethod] //删除雇员信息  
  60.        public void Delete(List<EmployeeModel> employee)  
  61.         {  
  62.             employee.ForEach(x => 
  63.             {  
  64.                 string CmdText = "DELETE FROM Employee WHERE EmployeeID="+x.EmployeeID.ToString();  
  65.                 SQLExcute(CmdText);  
  66.             });  
  67.         }  
  68.        //执行SQL命令文本,重载1  
  69.         private void SQLExcute(string SQLCmd)  
  70.         {  
  71.             string ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" + Server.MapPath(@"App_Data\Employees.mdb;");  
  72.             OleDbConnection Conn = new OleDbConnection(ConnectionString);  
  73.             Conn.Open();  
  74.             OleDbCommand Cmd = new OleDbCommand();  
  75.             Cmd.Connection = Conn;  
  76.             Cmd.CommandTimeout = 15;  
  77.             Cmd.CommandType = CommandType.Text;  
  78.             Cmd.CommandText = SQLCmd;  
  79.             Cmd.ExecuteNonQuery();  
  80.             Conn.Close();  
  81.         }  
  82.         //执行SQL命令文本,重载2  
  83.         private void SQLExcute(string SQLCmd,OleDbCommand Cmd)  
  84.         {  
  85.             string ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" + Server.MapPath(@"App_Data\Employees.mdb;");  
  86.             OleDbConnection Conn = new OleDbConnection(ConnectionString);  
  87.             Conn.Open();  
  88.             Cmd.Connection = Conn;  
  89.             Cmd.CommandTimeout = 15;  
  90.             Cmd.CommandType = CommandType.Text;  
  91.             Cmd.CommandText = SQLCmd;  
  92.             Cmd.ExecuteNonQuery();  
  93.         }  
  94.     }  

之后,在Silverlight客户端应用程序文件夹下,右击References文件夹,选择菜单选项Add Service Reference...。如下图所示,引入刚才我们创建的Web Service(别忘了按Discover按钮进行查找)。

创建Silverlight客户端应用程序
  1. MainPage.xaml文件  
  2. <UserControl 
  3. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   
  4.    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  5. xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"     mc:Ignorable="d" xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" xmlns:dataFormToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.DataForm.Toolkit" x:Class="SilverlightClient.MainPage" 
  6.  
  7.     d:DesignWidth="320" d:DesignHeight="240"> 
  8. <Grid x:Name="LayoutRoot" Width="320" Height="240" Background="White"> 
  9.  <dataFormToolkit:DataForm x:Name="dfEmployee" Margin="8,8,8,42"/> 
  10. <Button x:Name="btnGetData" Height="30" Margin="143,0,100,8" VerticalAlignment="Bottom" Content="Get Data" Width="77"/> 
  11. <Button x:Name="btnSaveAll" Height="30" Margin="0,0,8,8" VerticalAlignment="Bottom" Content="Save All" HorizontalAlignment="Right" Width="77"/> 
  12. <TextBlock x:Name="tbResult" Height="30" HorizontalAlignment="Left" Margin="8,0,0,8" VerticalAlignment="Bottom" Width="122" TextWrapping="Wrap" FontSize="16"/> 
  13. </Grid> 
  14. </UserControl> 
  15. MainPage.xaml.cs文件  
  16. using System;  
  17. using System.Collections.Generic;  
  18. using System.Collections.ObjectModel;  
  19. using System.Linq;  
  20. using System.Net;  
  21. using System.Windows;  
  22. using System.Windows.Controls;  
  23. using System.Windows.Documents;  
  24. using System.Windows.Input;  
  25. using System.Windows.Media;  
  26. using System.Windows.Media.Animation;  
  27. using System.Windows.Shapes;  
  28. using System.Xml;  
  29. using System.Xml.Linq;  
  30. using System.Windows.Browser;  
  31. using SilverlightClient.EmployeesInfoServiceReference;  
  32. namespace SilverlightClient  
  33. {  
  34.     public partial class MainPage : UserControl  
  35.     {  
  36.         int originalNum;//记录初始时的Employee表中的数据总数  
  37.         ObservableCollection<EmployeeModel> deletedID = new ObservableCollection<EmployeeModel>();//标记被删除的对象  
  38.        public MainPage()  
  39.         {  
  40.             InitializeComponent();  
  41.             this.Loaded += new RoutedEventHandler(MainPage_Loaded);  
  42.             this.btnGetData.Click += new RoutedEventHandler(btnGetData_Click);  
  43.             this.btnSaveAll.Click += new RoutedEventHandler(btnSaveAll_Click);   
  44.             this.dfEmployee.DeletingItem += new EventHandler<System.ComponentModel.CancelEventArgs>(dfEmployee_DeletingItem);  
  45.         }  
  46.         void dfEmployee_DeletingItem(object sender, System.ComponentModel.CancelEventArgs e)  
  47.         {  
  48.             deletedID.Add(dfEmployee.CurrentItem as EmployeeModel);//正在删除时,将被删除对象进行标记,以便传给服务端真正删除。  
  49.         }  
  50.         void btnSaveAll_Click(object sender, RoutedEventArgs e)  
  51.         {  
  52.             List<EmployeeModel> updateValues = dfEmployee.ItemsSource.Cast<EmployeeModel>().ToList();  
  53.             ObservableCollection<EmployeeModel> returnValues = new ObservableCollection<EmployeeModel>();  
  54.             if (updateValues.Count > originalNum)  
  55.             {  
  56.                 //添加数据  
  57.                 for (int i = originalNum; i <= updateValues.Count - 1; i++)  
  58.                 {  
  59.                     returnValues.Add(updateValues.ToArray()[i]);  
  60.                 }  
  61.                 EmployeesInfoWebServiceSoapClient webClient = new EmployeesInfoWebServiceSoapClient();  
  62.                 webClient.InsertCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(webClient_InsertCompleted);  
  63.                 webClient.InsertAsync(returnValues);  
  64.                 //必须考虑数据集中既有添加又有更新的情况  
  65.                 returnValues.Clear();  
  66.                 updateValues.ForEach(x => returnValues.Add(x));  
  67.                 webClient.UpdateCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(webClient_UpdateCompleted);  
  68.                 webClient.UpdateAsync(returnValues);  
  69.             }  
  70.             else if (updateValues.Count < originalNum)  
  71.             {  
  72.                 //删除数据  
  73.                 EmployeesInfoWebServiceSoapClient webClient = new EmployeesInfoWebServiceSoapClient();  
  74.                 webClient.DeleteCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(webClient_DeleteCompleted);  
  75.                 webClient.DeleteAsync(deletedID);  
  76.             }  
  77.             else  
  78.             {  
  79.                //更新数据  
  80.                 updateValues.ForEach(x => returnValues.Add(x));  
  81.                 EmployeesInfoWebServiceSoapClient webClient = new EmployeesInfoWebServiceSoapClient();  
  82.                 webClient.UpdateCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(webClient_UpdateCompleted);  
  83.                 webClient.UpdateAsync(returnValues);  
  84.            }  
  85.         }  
  86.         void webClient_UpdateCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)  
  87.         {  
  88.             tbResult.Text = "更新成功!";  
  89.         }  
  90.         void webClient_DeleteCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)  
  91.         {  
  92.             tbResult.Text = "删除成功!";  
  93.         }  
  94.         void webClient_InsertCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)  
  95.         {  
  96.             tbResult.Text = "添加成功!";  
  97.         }  
  98.         void btnGetData_Click(object sender, RoutedEventArgs e)  
  99.         {  
  100.             GetEmployees();  
  101.         }  
  102.         void MainPage_Loaded(object sender, RoutedEventArgs e)  
  103.         {  
  104.             GetEmployees();  
  105.         }  
  106.         void GetEmployees()  
  107.         {  
  108.             EmployeesInfoWebServiceSoapClient webClient = new EmployeesInfoWebServiceSoapClient();  
  109.             webClient.GetEmployeesInfoCompleted +=  
  110.             new EventHandler<GetEmployeesInfoCompletedEventArgs>(webClient_GetEmployeesInfoCompleted);  
  111.             webClient.GetEmployeesInfoAsync();  
  112.         }  
  113.         void webClient_GetEmployeesInfoCompleted(object sender, GetEmployeesInfoCompletedEventArgs e)  
  114.         {  
  115.             originalNum = e.Result.Count;//记录原始数据个数  
  116.             dfEmployee.ItemsSource = e.Result;  
  117.         }  
  118.     }  

最终效果图


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3