首页 > 数据库 > Access > 正文

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

2020-03-24 17:49:40
字体:
来源:转载
供稿:网友
Silverlight与Access互操作是一个很基础的问题,主要涉及到数据库的操作。Access属于轻量级的数据库,应用起来还是比较方便的。51CTO编辑推荐《走向银光 —— 一步一步学Silverlight》 在开发一些小型html' target='_blank'>应用程序时,我们就需要使用一些小巧的轻量级的数据库,比如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文件(放置在服务端项目文件夹下)usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; namespacedatagridnaccessdb { publicclassEmployeeModel { publicintEmployeeID{get;set;} publicstringEmployeeName{get;set;} publicintEmployeeAge{get;set;} } }建立服务端Web Service★右击服务端项目文件夹,选择Add- New Item....,按下图所示建立一个名为EmployeesInfoWebService.asmx的Web Service,作为Silverlight与Access数据库互操作的桥梁。创建完毕后,双击EmployeesInfoWebService.asmx打开该文件。将里面的内容修改如下:usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Web; usingSystem.Web.Services; usingSystem.Data.OleDb;//引入该命名空间为了操作Access数据库 usingSystem.Data; namespacedatagridnaccessdb { /// summary ///SummarydescriptionforEmployeesInfoWebService /// /summary [WebService(Namespace="http://tempuri.org/")] [WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] //ToallowthisWebServicetobecalledfromscript,usingASP.NETAJAX,uncommentthefollowingline. //[System.Web.Script.Services.ScriptService] publicclassEmployeesInfoWebService:System.Web.Services.WebService { [WebMethod]//获取雇员信息 publicList EmployeeModel GetEmployeesInfo() { List EmployeeModel returnedValue=newList EmployeeModel (); OleDbCommandCmd=newOleDbCommand(); SQLExcute("SELECT*FROMEmployee",Cmd); OleDbDataAdapterEmployeeAdapter=newOleDbDataAdapter(); EmployeeAdapter.SelectCommand=Cmd; DataSetEmployeeDataSet=newDataSet(); EmployeeAdapter.Fill(EmployeeDataSet); foreach(DataRowdrinEmployeeDataSet.Tables[0].Rows) { EmployeeModeltmp=newEmployeeModel(); tmp.EmployeeID=Convert.ToInt32(dr[0]); tmp.EmployeeName=Convert.ToString(dr[1]); tmp.EmployeeAge=Convert.ToInt32(dr[2]); returnedValue.Add(tmp); } returnreturnedValue; } [WebMethod]//添加雇员信息 publicvoidInsert(List EmployeeModel employee) { employee.ForEach(x= { stringCmdText="INSERTINTOEmployee(EmployeeName,EmployeeAge)VALUES('"+x.EmployeeName+"',"+x.EmployeeAge.ToString()+")"; SQLExcute(CmdText); }); } [WebMethod]//更新雇员信息 publicvoidUpdate(List EmployeeModel employee) { employee.ForEach(x= { stringCmdText="UPDATEEmployeeSETEmployeeName='"+x.EmployeeName+"',EmployeeAge="+x.EmployeeAge.ToString(); CmdText+="WHEREEmployeeID="+x.EmployeeID.ToString(); SQLExcute(CmdText); }); } [WebMethod]//删除雇员信息 publicvoidDelete(List EmployeeModel employee) { employee.ForEach(x= { stringCmdText="DELETEFROMEmployeeWHEREEmployeeID="+x.EmployeeID.ToString(); SQLExcute(CmdText); }); } //执行SQL命令文本,重载1 privatevoidSQLExcute(stringSQLCmd) { stringConnectionString="PROVIDER=Microsoft.Jet.OLEDB.4.0;DATASOURCE="+Server.MapPath(@"App_Data/Employees.mdb;"); OleDbConnectionConn=newOleDbConnection(ConnectionString); Conn.Open(); OleDbCommandCmd=newOleDbCommand(); Cmd.Connection=Conn; Cmd.CommandTimeout=15; Cmd.CommandType=CommandType.Text; Cmd.CommandText=SQLCmd; Cmd.ExecuteNonQuery(); Conn.Close(); } //执行SQL命令文本,重载2 privatevoidSQLExcute(stringSQLCmd,OleDbCommandCmd) { stringConnectionString="PROVIDER=Microsoft.Jet.OLEDB.4.0;DATASOURCE="+Server.MapPath(@"App_Data/Employees.mdb;"); OleDbConnectionConn=newOleDbConnection(ConnectionString); Conn.Open(); Cmd.Connection=Conn; Cmd.CommandTimeout=15; Cmd.CommandType=CommandType.Text; Cmd.CommandText=SQLCmd; Cmd.ExecuteNonQuery(); } } }之后,在Silverlight客户端应用程序文件夹下,右击References文件夹,选择菜单选项Add Service Reference...。如下图所示,引入刚才我们创建的Web Service(别忘了按Discover按钮进行查找)。创建Silverlight客户端应用程序MainPage.xaml文件 UserControlxmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"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: d:DesignWidth="320"d:DesignHeight="240" Gridx:Name="LayoutRoot"Width="320"Height="240"Background="White" dataFormToolkit:DataFormx:Name="dfEmployee"Margin="8,8,8,42"/ Buttonx:Name="btnGetData"Height="30"Margin="143,0,100,8"VerticalAlignment="Bottom"Content="GetData"Width="77"/ Buttonx:Name="btnSaveAll"Height="30"Margin="0,0,8,8"VerticalAlignment="Bottom"Content="SaveAll"HorizontalAlignment="Right"Width="77"/ TextBlockx:Name="tbResult"Height="30"HorizontalAlignment="Left"Margin="8,0,0,8"VerticalAlignment="Bottom"Width="122"TextWrapping="Wrap"FontSize="16"/ /Grid /UserControl MainPage.xaml.cs文件 usingSystem; usingSystem.Collections.Generic; usingSystem.Collections.ObjectModel; usingSystem.Linq; usingSystem.Net; usingSystem.Windows; usingSystem.Windows.Controls; usingSystem.Windows.Documents; usingSystem.Windows.Input; usingSystem.Windows.Media; usingSystem.Windows.Media.Animation; usingSystem.Windows.Shapes; usingSystem.Xml; usingSystem.Xml.Linq; usingSystem.Windows.Browser; usingSilverlightClient.EmployeesInfoServiceReference; namespaceSilverlightClient { publicpartialclassMainPage:UserControl { intoriginalNum;//记录初始时的Employee表中的数据总数 ObservableCollection EmployeeModel deletedID=newObservableCollection EmployeeModel ();//标记被删除的对象 publicMainPage() { InitializeComponent(); this.Loaded+=newRoutedEventHandler(MainPage_Loaded); this.btnGetData.Click+=newRoutedEventHandler(btnGetData_Click); this.btnSaveAll.Click+=newRoutedEventHandler(btnSaveAll_Click); this.dfEmployee.DeletingItem+=newEventHandler System.ComponentModel.CancelEventArgs (dfEmployee_DeletingItem); } voiddfEmployee_DeletingItem(objectsender,System.ComponentModel.CancelEventArgse) { deletedID.Add(dfEmployee.CurrentItemasEmployeeModel);//正在删除时,将被删除对象进行标记,以便传给服务端真正删除。 } voidbtnSaveAll_Click(objectsender,RoutedEventArgse) { List EmployeeModel updateValues=dfEmployee.ItemsSource.Cast EmployeeModel ().ToList(); ObservableCollection EmployeeModel returnValues=newObservableCollection EmployeeModel (); if(updateValues.Count originalNum) { //添加数据 for(inti=originalNum;i =updateValues.Count-1;i++) { returnValues.Add(updateValues.ToArray()[i]); } EmployeesInfoWebServiceSoapClientwebClient=newEmployeesInfoWebServiceSoapClient(); webClient.InsertCompleted+=newEventHandler System.ComponentModel.AsyncCompletedEventArgs (webClient_InsertCompleted); webClient.InsertAsync(returnValues); //必须考虑数据集中既有添加又有更新的情况 returnValues.Clear(); updateValues.ForEach(x= returnValues.Add(x)); webClient.UpdateCompleted+=newEventHandler System.ComponentModel.AsyncCompletedEventArgs (webClient_UpdateCompleted); webClient.UpdateAsync(returnValues); } elseif(updateValues.Count originalNum) { //删除数据 EmployeesInfoWebServiceSoapClientwebClient=newEmployeesInfoWebServiceSoapClient(); webClient.DeleteCompleted+=newEventHandler System.ComponentModel.AsyncCompletedEventArgs (webClient_DeleteCompleted); webClient.DeleteAsync(deletedID); } else { //更新数据 updateValues.ForEach(x= returnValues.Add(x)); EmployeesInfoWebServiceSoapClientwebClient=newEmployeesInfoWebServiceSoapClient(); webClient.UpdateCompleted+=newEventHandler System.ComponentModel.AsyncCompletedEventArgs (webClient_UpdateCompleted); webClient.UpdateAsync(returnValues); } } voidwebClient_UpdateCompleted(objectsender,System.ComponentModel.AsyncCompletedEventArgse) { tbResult.Text="更新成功!"; } voidwebClient_DeleteCompleted(objectsender,System.ComponentModel.AsyncCompletedEventArgse) { tbResult.Text="删除成功!"; } voidwebClient_InsertCompleted(objectsender,System.ComponentModel.AsyncCompletedEventArgse) { tbResult.Text="添加成功!"; } voidbtnGetData_Click(objectsender,RoutedEventArgse) { GetEmployees(); } voidMainPage_Loaded(objectsender,RoutedEventArgse) { GetEmployees(); } voidGetEmployees() { EmployeesInfoWebServiceSoapClientwebClient=newEmployeesInfoWebServiceSoapClient(); webClient.GetEmployeesInfoCompleted+= newEventHandler GetEmployeesInfoCompletedEventArgs (webClient_GetEmployeesInfoCompleted); webClient.GetEmployeesInfoAsync(); } voidwebClient_GetEmployeesInfoCompleted(objectsender,GetEmployeesInfoCompletedEventArgse) { originalNum=e.Result.Count;//记录原始数据个数 dfEmployee.ItemsSource=e.Result; } } }最终效果图html教程

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表