详解Silverlight与Access互操作的具体实现
创始人
2024-06-06 08:51:40
0
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数据库互操作的桥梁。

建立服务端Web Service

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

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

选择菜单选项Add Service Reference

创建Silverlight客户端应用程序
  1. MainPage.xaml文件  
  2.  
  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.  x:Name="LayoutRoot" Width="320" Height="240" Background="White"> 
  9.   x:Name="dfEmployee" Margin="8,8,8,42"/> 
  10.  x:Name="btnGetData" Height="30" Margin="143,0,100,8" VerticalAlignment="Bottom" Content="Get Data" Width="77"/> 
  11.  x:Name="btnSaveAll" Height="30" Margin="0,0,8,8" VerticalAlignment="Bottom" Content="Save All" HorizontalAlignment="Right" Width="77"/> 
  12.  x:Name="tbResult" Height="30" HorizontalAlignment="Left" Margin="8,0,0,8" VerticalAlignment="Bottom" Width="122" TextWrapping="Wrap" FontSize="16"/> 
  13.  
  14.  
  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 deletedID = new ObservableCollection();//标记被删除的对象  
  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(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 updateValues = dfEmployee.ItemsSource.Cast().ToList();  
  53.             ObservableCollection returnValues = new ObservableCollection();  
  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(webClient_InsertCompleted);  
  63.                 webClient.InsertAsync(returnValues);  
  64.                 //必须考虑数据集中既有添加又有更新的情况  
  65.                 returnValues.Clear();  
  66.                 updateValues.ForEach(x => returnValues.Add(x));  
  67.                 webClient.UpdateCompleted += new EventHandler(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(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(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(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.     }  

最终效果图

最终效果图

 

原文标题:Silverlight与Access数据库的互操作(CURD完全解析)

链接:http://www.cnblogs.com/Kinglee/archive/2009/09/05/1561021.html

【编辑推荐】

  1. Office 2010将使用Silverlight改善用户体验
  2. 微软.NET平台主管谈Silverlight企业级开发
  3. Flash与Silverlight多领域实测对比
  4. 微软宣称Silverlight装机量超过三亿
  5. 图解Silverlight 3的7个新功能

相关内容

热门资讯

如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
施耐德电气数据中心整体解决方案... 近日,全球能效管理专家施耐德电气正式启动大型体验活动“能效中国行——2012卡车巡展”,作为该活动的...
20个非常棒的扁平设计免费资源 Apple设备的平面图标PSD免费平板UI 平板UI套件24平图标Freen平板UI套件PSD径向平...
德国电信门户网站可实时显示全球... 德国电信周三推出一个门户网站,直观地实时提供其安装在全球各地的传感器网络检测到的网络攻击状况。该网站...
为啥国人偏爱 Mybatis,... 关于 SQL 和 ORM 的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行...
《非诚勿扰》红人闫凤娇被曝厕所... 【51CTO.com 综合消息360安全专家提醒说,“闫凤娇”、“非诚勿扰”已经被黑客盯上成为了“木...
2012年第四季度互联网状况报... [[71653]]  北京时间4月25日消息,据国外媒体报道,全球知名的云平台公司Akamai Te...