[源码下载]
稳扎稳打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://www.voidcn.com/article/p-ounmxjds-tq.html
示例
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,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();
}
}
}
} OK
[源码下载] 总结
以上是内存溢出为你收集整理的稳扎稳打Silverlight(28) - 2.0通信之调用ADO.NET Data Services(数据服务)全部内容,希望文章能够帮你解决稳扎稳打Silverlight(28) - 2.0通信之调用ADO.NET Data Services(数据服务)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)