稳扎稳打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
using System; 
using System.Collections.Generic; 
using System.Data.Services; 
using System.Linq; 
using System.ServiceModel.Web; 
using System.Web; 
 
namespace Silverlight20.Web.DataService 

         public  class NorthwindDataService : DataService<NorthwindEntities> 
        { 
                 public  static  void InitializeService(IDataServiceConfiguration config) 
                { 
                        config.SetEntitySetAccessRule( "*", EntitySetRights.All); 
                } 
        } 
}
 
 
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
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Animation; 
using System.Windows.Shapes; 
 
using System.Data.Services.Client; 
using System.Collections.ObjectModel; 
using Silverlight20.NorthwindDataService; 
 
namespace Silverlight20.Communication 

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




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

热门文章

最新文章

下一篇
无影云桌面