稳扎稳打Silverlight(28) - 2.0通信之调用ADO.NET Data Services(数据服务)

简介:

[索引页]

[源码下载]


稳扎稳打Silverlight(28) - 2.0通信之调用ADO.NET Data Services(数据服务)


作者: webabcd


介绍
Silverlight 2.0 调用 ADO.NET Data Services (数据服务)。本文以 Northwind 数据库为示例数据库,做一个添加、查询、更新和删除的Demo 
    在 Silverlight 2.0 中调用数据服务只能使用异步方式调用。另外,数据服务要与 Silverlight 宿主放在相同的域上
    System.Data.Services.Client.DataServiceContext - 数据服务上下文
    System.Data.Services.Client.DataServiceQuery - 以指定的 URI 语法查询数据服务
    AddObject(), UpdateObject(), DeleteObject() - 本别用于添加, 更新, 删除实体
    BeginExecute()/EndExecute(), BeginExecuteBatch()/EndExecuteBatch - 用于执行某一个 DataServiceQuery 查询或批量执行(将一组查询一次性地提交到数据服务)
    BeginSaveChanges()/EndSaveChanges() - 用于提交对实体的修改(增,删,改)
    BeginLoadProperty()/EndLoadProperty() - 用于加载指定的属性的值,加载导航属性的时候需要用到它
    AddLink(), SetLink(), DeleteLink() - 分别为创建连接,Added状态(一对多);创建连接,Added状态(多对一);删除连接,Deleted状态


在线DEMO
http://webabcd.blog.51cto.com/1787395/342779 


示例
1、数据服务
NorthwindDataService.svc
<%@ ServiceHost Language="C#" Factory="System.Data.Services.DataServiceHostFactory, System.Data.Services, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Service="Silverlight20.Web.DataService.NorthwindDataService" %>
 
NorthwindDataService.svc.cs
InBlock.gif using System; 
InBlock.gif using System.Collections.Generic; 
InBlock.gif using System.Data.Services; 
InBlock.gif using System.Linq; 
InBlock.gif using System.ServiceModel.Web; 
InBlock.gif using System.Web; 
InBlock.gif 
InBlock.gif namespace Silverlight20.Web.DataService 
InBlock.gif
InBlock.gif         public  class NorthwindDataService : DataService<NorthwindEntities> 
InBlock.gif        { 
InBlock.gif                 public  static  void InitializeService(IDataServiceConfiguration config) 
InBlock.gif                { 
InBlock.gif                        config.SetEntitySetAccessRule( "*", EntitySetRights.All); 
InBlock.gif                } 
InBlock.gif        } 
InBlock.gif}
 
 
2、Silverlight 调用数据服务
DataService.xaml
<UserControl x:Class="Silverlight20.Communication.DataService" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"> 

        <StackPanel HorizontalAlignment="Left" Margin="5"> 

                <TextBlock x:Name="lblMsg" Margin="10" Foreground="Red" /> 

                <StackPanel Orientation="Horizontal"> 
                        <TextBlock x:Name="lblCategoryName" Text="类别名称" Margin="10" /> 
                        <TextBox x:Name="txtCategoryName" Width="100" Margin="10" /> 
                        <TextBlock x:Name="lblDescription" Text="类别备注" Margin="10" /> 
                        <TextBox x:Name="txtDescription" Width="100" Margin="10" /> 
                        <Button x:Name="btnAdd" Content="添加" Margin="10" Click="btnAdd_Click" /> 
                </StackPanel> 

                <StackPanel Orientation="Horizontal"> 
                        <Button x:Name="btnUpdate" Content="更新选中" Margin="10" Click="btnUpdate_Click" /> 
                        <Button x:Name="btnDelete" Content="删除选中" Margin="10" Click="btnDelete_Click"    /> 
                </StackPanel> 

                <data:DataGrid Name="dataGrid1" Margin="10" AutoGenerateColumns="False" ItemsSource="{Binding}" 
                        SelectionChanged="DataGrid_SelectionChanged"> 
                        <data:DataGrid.Columns> 
                                <data:DataGridTextColumn Header="类别ID" Binding="{Binding CategoryID}" /> 
                                <data:DataGridTextColumn Header="类别名称" Binding="{Binding CategoryName}" /> 
                                <data:DataGridTextColumn Header="类别备注" Binding="{Binding Description}" /> 
                        </data:DataGrid.Columns> 
                </data:DataGrid> 

                <data:DataGrid Name="dataGrid2" Margin="10" AutoGenerateColumns="False" ItemsSource="{Binding}"> 
                        <data:DataGrid.Columns> 
                                <data:DataGridTextColumn Header="产品ID" Binding="{Binding ProductID}" /> 
                                <data:DataGridTextColumn Header="产品名称" Binding="{Binding ProductName}" /> 
                        </data:DataGrid.Columns> 
                </data:DataGrid> 

        </StackPanel> 

</UserControl>
 
DataService.xaml.cs
InBlock.gif using System; 
InBlock.gif using System.Collections.Generic; 
InBlock.gif using System.Linq; 
InBlock.gif using System.Net; 
InBlock.gif using System.Windows; 
InBlock.gif using System.Windows.Controls; 
InBlock.gif using System.Windows.Documents; 
InBlock.gif using System.Windows.Input; 
InBlock.gif using System.Windows.Media; 
InBlock.gif using System.Windows.Media.Animation; 
InBlock.gif using System.Windows.Shapes; 
InBlock.gif 
InBlock.gif using System.Data.Services.Client; 
InBlock.gif using System.Collections.ObjectModel; 
InBlock.gif using Silverlight20.NorthwindDataService; 
InBlock.gif 
InBlock.gif namespace Silverlight20.Communication 
InBlock.gif
InBlock.gif         public partial  class DataService : UserControl 
InBlock.gif        { 
InBlock.gif                 // 配置服务地址,数据服务要与 Silverlight 宿主放在相同的域上 
InBlock.gif                Uri uri =  new Uri( "DataService/NorthwindDataService.svc", UriKind.Relative); 
InBlock.gif                NorthwindEntities ctx; 
InBlock.gif                ObservableCollection<Categories> categories; 
InBlock.gif                ObservableCollection<Products> products; 
InBlock.gif 
InBlock.gif                 public DataService() 
InBlock.gif                { 
InBlock.gif                        InitializeComponent(); 
InBlock.gif 
InBlock.gif                         this.Loaded +=  new RoutedEventHandler(DataService_Loaded); 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                 void DataService_Loaded( object sender, RoutedEventArgs e) 
InBlock.gif                { 
InBlock.gif                         // 实例化 DataServiceContext 
InBlock.gif                        ctx =  new NorthwindEntities(uri); 
InBlock.gif                         // 初始化 Categories 集合,为了做 OneWay ,所以是 ObservableCollection<Categories> 类型 
InBlock.gif                        categories =  new ObservableCollection<Categories>(); 
InBlock.gif                         // 初始化 Products 集合,为了做 OneWay ,所以是 ObservableCollection<Products> 类型 
InBlock.gif                        products =  new ObservableCollection<Products>(); 
InBlock.gif 
InBlock.gif                        BindCategory(); 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                 private  void BindCategory() 
InBlock.gif                { 
InBlock.gif                        DataServiceQuery<Categories> query = ctx.Categories; 
InBlock.gif 
InBlock.gif                         // IAsyncResult BeginExecute(AsyncCallback callback, object state) - 以异步方式发出请求 
InBlock.gif                         //         AsyncCallback callback - 经典的 AsyncCallback 委托,指定回调方法 
InBlock.gif                         //         object state - 传递给回调方法的自定义对象,此处必须是 DataServiceQuery<T> 类型 
InBlock.gif                        query.BeginExecute(OnBindCategoryCompleted, query); 
InBlock.gif                         // RequestUri - 请求服务的地址,因为数据服务发布的是REST,所以也可以用自己构造 URI 的方式去调用数据服务,详细的 URI 语法请参看 MSDN 
InBlock.gif                        lblMsg.Text =  "读取类别数据中。。。" + query.RequestUri.ToString(); 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                 void OnBindCategoryCompleted(IAsyncResult ar) 
InBlock.gif                { 
InBlock.gif                         try 
InBlock.gif                        { 
InBlock.gif                                var query = ar.AsyncState  as DataServiceQuery<Categories>; 
InBlock.gif 
InBlock.gif                                 // EndExecute(IAsyncResult ar) - 获取异步查询的结果 
InBlock.gif                                var result = query.EndExecute(ar); 
InBlock.gif 
InBlock.gif                                 foreach (var item  in result) 
InBlock.gif                                { 
InBlock.gif                                        categories.Add(item); 
InBlock.gif                                } 
InBlock.gif 
InBlock.gif                                 this.Dispatcher.BeginInvoke(() => 
InBlock.gif                                { 
InBlock.gif                                        dataGrid1.DataContext = categories; 
InBlock.gif                                        lblMsg.Text = ""; 
InBlock.gif                                }); 
InBlock.gif                        } 
InBlock.gif                         catch (DataServiceRequestException ex) 
InBlock.gif                        { 
InBlock.gif                                lblMsg.Text = ex.ToString(); 
InBlock.gif                        } 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                 private  void btnAdd_Click( object sender, RoutedEventArgs e) 
InBlock.gif                { 
InBlock.gif                        Categories category =  new Categories(); 
InBlock.gif                        category.CategoryName = txtCategoryName.Text; 
InBlock.gif                        category.Description = txtDescription.Text; 
InBlock.gif 
InBlock.gif                        ctx.AddToCategories(category); 
InBlock.gif 
InBlock.gif                         for ( int i = 0; i < 10; i++) 
InBlock.gif                        { 
InBlock.gif                                var product =  new Products() { ProductName =  "测试用" + i.ToString() }; 
InBlock.gif                                product.Categories = category; 
InBlock.gif                                ctx.AddToProducts(product); 
InBlock.gif                                 // 多对一关系,使用 SetLink 建立连接,BeginSaveChanges() 的时候会一起发送到数据服务 
InBlock.gif                                ctx.SetLink(product,  "Categories", category); 
InBlock.gif                        } 
InBlock.gif 
InBlock.gif                        ctx.BeginSaveChanges(OnAddCompleted, category); 
InBlock.gif                        lblMsg.Text =  "新增数据中。。。"
InBlock.gif                } 
InBlock.gif 
InBlock.gif                 void OnAddCompleted(IAsyncResult ar) 
InBlock.gif                { 
InBlock.gif                         try 
InBlock.gif                        { 
InBlock.gif                                var x = ctx.EndSaveChanges(ar); 
InBlock.gif 
InBlock.gif                                categories.Add(ar.AsyncState  as Categories); 
InBlock.gif 
InBlock.gif                                 this.Dispatcher.BeginInvoke(() => 
InBlock.gif                                { 
InBlock.gif                                        lblMsg.Text = ""; 
InBlock.gif                                }); 
InBlock.gif                        } 
InBlock.gif                         catch (DataServiceRequestException ex) 
InBlock.gif                        { 
InBlock.gif                                lblMsg.Text = ex.ToString(); 
InBlock.gif                        } 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                 private  void DataGrid_SelectionChanged( object sender, SelectionChangedEventArgs e) 
InBlock.gif                { 
InBlock.gif                        var category = e.AddedItems[0]  as Categories; 
InBlock.gif                        BindProduct(category.CategoryID); 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                 private  void BindProduct( int categoryId) 
InBlock.gif                { 
InBlock.gif                         // 可以使用 Lambda 表达式或查询语法,然后将其转换为 DataServiceQuery<T> 再使用 
InBlock.gif                        DataServiceQuery<Products> query = 
InBlock.gif                                (from p  in ctx.Products where p.Categories.CategoryID == categoryId select p)  as DataServiceQuery<Products>; 
InBlock.gif 
InBlock.gif                        lblMsg.Text =  "读取产品数据中。。。"
InBlock.gif                        query.BeginExecute(OnBindProductCompleted, query); 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                 void OnBindProductCompleted(IAsyncResult ar) 
InBlock.gif                { 
InBlock.gif                         try 
InBlock.gif                        { 
InBlock.gif                                var query = ar.AsyncState  as DataServiceQuery<Products>; 
InBlock.gif 
InBlock.gif                                var result = query.EndExecute(ar); 
InBlock.gif                                products.Clear(); 
InBlock.gif                                 foreach (var item  in result) 
InBlock.gif                                { 
InBlock.gif                                        products.Add(item); 
InBlock.gif                                } 
InBlock.gif 
InBlock.gif                                 this.Dispatcher.BeginInvoke(() => 
InBlock.gif                                { 
InBlock.gif                                        dataGrid2.DataContext = products; 
InBlock.gif                                        lblMsg.Text = ""; 
InBlock.gif                                }); 
InBlock.gif                        } 
InBlock.gif                         catch (DataServiceRequestException ex) 
InBlock.gif                        { 
InBlock.gif                                lblMsg.Text = ex.ToString(); 
InBlock.gif                        } 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                 private  void btnDelete_Click( object sender, RoutedEventArgs e) 
InBlock.gif                { 
InBlock.gif                         if (dataGrid1.SelectedItem !=  null
InBlock.gif                        { 
InBlock.gif                                 try 
InBlock.gif                                { 
InBlock.gif                                        Categories category = dataGrid1.SelectedItem  as Categories; 
InBlock.gif 
InBlock.gif                                        DeleteCategory(category); 
InBlock.gif                                        lblMsg.Text =  "删除中。。。"
InBlock.gif                                } 
InBlock.gif                                 catch (DataServiceRequestException ex) 
InBlock.gif                                { 
InBlock.gif                                        lblMsg.Text = ex.ToString(); 
InBlock.gif                                } 
InBlock.gif                        } 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                 private  void DeleteCategory(Categories category) 
InBlock.gif                { 
InBlock.gif                         try 
InBlock.gif                        { 
InBlock.gif                                 // BeginLoadProperty(object entity, string propertyName, AsyncCallback callback, object state) - 开始加载指定属性的值的异步操作 
InBlock.gif                                 //         object entity - 需要加载属性的所属实体    
InBlock.gif                                 //         string propertyName - 需要加载属性的名称 
InBlock.gif                                 //         AsyncCallback callback - 经典的 AsyncCallback 委托,指定回调方法 
InBlock.gif                                 //         object state - 传递给回调方法的自定义对象 
InBlock.gif                                ctx.BeginLoadProperty(category,  "Products", OnLoadPropertyCompleted, category); 
InBlock.gif                        } 
InBlock.gif                         catch (DataServiceRequestException ex) 
InBlock.gif                        { 
InBlock.gif                                lblMsg.Text = ex.ToString(); 
InBlock.gif                        } 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                 void OnLoadPropertyCompleted(IAsyncResult ar) 
InBlock.gif                { 
InBlock.gif                        Categories category = ar.AsyncState  as Categories; 
InBlock.gif 
InBlock.gif                         try 
InBlock.gif                        { 
InBlock.gif                                 // EndLoadProperty(IAsyncResult ar) - 完成加载指定属性的值的这个异步操作 
InBlock.gif                                ctx.EndLoadProperty(ar); 
InBlock.gif 
InBlock.gif                                 foreach (Products product  in category.Products) 
InBlock.gif                                { 
InBlock.gif                                         // 在指定的对象上删除指定的连接,BeginSaveChanges() 的时候会一起发送到数据服务 
InBlock.gif                                        ctx.DeleteLink(category,  "Products", product); 
InBlock.gif                                } 
InBlock.gif 
InBlock.gif                                ctx.DeleteObject(category); 
InBlock.gif                                ctx.BeginSaveChanges(OnDeleteCategoryCompleted,  null); 
InBlock.gif 
InBlock.gif                                categories.Remove(category); 
InBlock.gif                        } 
InBlock.gif                         catch (DataServiceRequestException ex) 
InBlock.gif                        { 
InBlock.gif                                lblMsg.Text = ex.ToString(); 
InBlock.gif                        } 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                 void OnDeleteCategoryCompleted(IAsyncResult ar) 
InBlock.gif                { 
InBlock.gif                         try 
InBlock.gif                        { 
InBlock.gif                                ctx.EndSaveChanges(ar); 
InBlock.gif                                lblMsg.Text = ""; 
InBlock.gif 
InBlock.gif                        } 
InBlock.gif                         catch (DataServiceRequestException ex) 
InBlock.gif                        { 
InBlock.gif                                lblMsg.Text = ex.ToString(); 
InBlock.gif                        } 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                 private  void btnUpdate_Click( object sender, RoutedEventArgs e) 
InBlock.gif                { 
InBlock.gif                         if (dataGrid1.SelectedItem !=  null
InBlock.gif                        { 
InBlock.gif                                 try 
InBlock.gif                                { 
InBlock.gif                                        Categories category = dataGrid1.SelectedItem  as Categories; 
InBlock.gif 
InBlock.gif                                        ctx.UpdateObject(category); 
InBlock.gif                                        ctx.BeginSaveChanges(OnUpdateCategoryCompleted, category); 
InBlock.gif                                        lblMsg.Text =  "更新中。。。"
InBlock.gif                                } 
InBlock.gif                                 catch (DataServiceRequestException ex) 
InBlock.gif                                { 
InBlock.gif                                        lblMsg.Text = ex.ToString(); 
InBlock.gif                                } 
InBlock.gif                        } 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                 void OnUpdateCategoryCompleted(IAsyncResult ar) 
InBlock.gif                { 
InBlock.gif                         try 
InBlock.gif                        { 
InBlock.gif                                ctx.EndSaveChanges(ar); 
InBlock.gif                                lblMsg.Text = ""; 
InBlock.gif 
InBlock.gif                        } 
InBlock.gif                         catch (DataServiceRequestException ex) 
InBlock.gif                        { 
InBlock.gif                                lblMsg.Text = ex.ToString(); 
InBlock.gif                        } 
InBlock.gif                } 
InBlock.gif        } 
InBlock.gif}
 
 




     本文转自webabcd 51CTO博客,原文链接: http://blog.51cto.com/webabcd/343917 ,如需转载请自行联系原作者
 
相关文章
|
12月前
|
关系型数据库 MySQL 数据库
找不到请求的 .Net Framework Data Provider。可能没有安装
做的一个项目,框架为.net framework 数据库为mysql 出现如标题错误 检查是否安装mysql、是否安装mysql connector net 笔者是因为没有安装后者mysql connector net 下载地址: [mysql connector net](https://downloads.mysql.com/archives/c-net/ "mysql connector net") 笔者安装截图如下: ![请在此添加图片描述](https://developer-private-1258344699.cos.ap-guangzhou.myqcloud.com/c
170 0
|
物联网 Linux 开发工具
Net Core 跨平台应用使用串口、串口道通信,可能出现的问题、更简洁的实现方法
Net Core 跨平台应用使用串口、串口道通信,可能出现的问题、更简洁的实现方法
418 0
Net Core 跨平台应用使用串口、串口道通信,可能出现的问题、更简洁的实现方法
|
监控 物联网 API
【.NET+MQTT】.NET6 环境下实现MQTT通信,以及服务端、客户端的双边消息订阅与发布的代码演示
MQTT广泛应用于工业物联网、智能家居、各类智能制造或各类自动化场景等。MQTT是一个基于客户端-服务器的消息发布/订阅传输协议,在很多受限的环境下,比如说机器与机器通信、机器与物联网通信等。好了,科普的废话不多说,下面直接通过.NET环境来实现一套MQTT通信demo,实现服务端与客户端的双边消息发布与订阅的功能和演示。
1240 0
【.NET+MQTT】.NET6 环境下实现MQTT通信,以及服务端、客户端的双边消息订阅与发布的代码演示
|
2月前
|
开发框架 .NET API
.Net Core Console 项目如何使用 HttpClient 与 Web 服务通信
.Net Core Console 项目如何使用 HttpClient 与 Web 服务通信
|
4月前
|
Linux Docker 容器
蓝易云 - net.ipv4.ip_forward=0导致docker容器无法与外部通信
完成以上步骤后,Docker容器应该能够正常与外部通信了。
155 2
|
5月前
|
数据挖掘 定位技术
.NET Compact Framework下的GPS NMEA data数据分析(二)转
.NET Compact Framework下的GPS NMEA data数据分析(二)转
38 0
|
网络协议 安全 Java
.NET网络编程——TCP通信
.NET网络编程——TCP通信
84 0
|
消息中间件 安全 数据库连接
.NET开发问题记录——TransactionScope出错:“与基础事务管理器的通信失败”的解决方法
.NET开发问题记录——TransactionScope出错:“与基础事务管理器的通信失败”的解决方法
267 0
|
存储 数据采集 网络协议
【.NET6+Modbus】Modbus TCP协议解析、仿真环境以及基于.NET实现基础通信
随着工业化的发展,目前越来越多的开发,从互联网走向传统行业。其中,工业领域也是其中之一,包括各大厂也都在陆陆续续加入工业4.0的进程当中。
359 0
【.NET6+Modbus】Modbus TCP协议解析、仿真环境以及基于.NET实现基础通信
|
存储 开发框架 JavaScript
『SignalR』.NET使用 SignalR 进行实时通信初体验
📣读完这篇文章里你能收获到 - 你将对SignalR有了初步的认识及体会 - 对于哪些场景适用SignalR以及如何接入使用 - SignalR的代码入门级Demo实际案例
590 0
『SignalR』.NET使用 SignalR 进行实时通信初体验