DomainDataSource控件是很强大的,排序/分组/分页等都能轻松搞定。控件的使用可以参考MSDN的文档,已经很详细了。
值得注意的是:其分页功能是“服务器段分页”,而不是一次性将数据下载到客户端去分页。我做过试验,客户端分页如果数据超过3500行,直接报错(使用的DataGrid和DataPager显示数据,WCF RIA Service传递数据)。而DomainDataSource控件采用服务器分页就没有此问题,并且分页是自动的,不需要自己手动Skip,Take了。为了验证DomainDataSource控件是如何做到服务器端分页的,我们可以使用Sql Server Profiler工具,对传到服务器端的SQL语句进行跟踪。
1、打开Sql Server Profiler,新建跟踪,选择数据库,开始跟踪
2、示例程序很简单,使用的Sql Server 2005自带的AdventureWorks数据库。DomainService代码:
[EnableClientAccess()] public class CustomerService : LinqToEntitiesDomainService<AdventureWorksEntities> { public IQueryable<Customer> GetCustomer() { return this.ObjectContext.Customer.OrderBy(c => c.CustomerID); } }
如果要使用分页功能,必须OrderBy我们的数据。客户端数据:
<Grid x:Name="LayoutRoot" Background="White"> <ria:DomainDataSource x:Name="Source" PageSize="15" LoadSize="30" QueryName="GetCustomer" AutoLoad="True"> <ria:DomainDataSource.DomainContext> <sv:CustomerContext/> </ria:DomainDataSource.DomainContext> </ria:DomainDataSource> <StackPanel> <data:DataGrid ItemsSource="{Binding Data,ElementName=Source}"/> <data:DataPager Source="{Binding Data,ElementName=Source}"/> </StackPanel> </Grid>
3、运行示例程序:将近2万行数据Silverlight没有崩溃的,这得益于"服务器端分页“,按需加载。
、
这里我们设置了每次查询加载30行数据,每页显示15行,也就是说每翻2页查询一次数据库。
4、多翻几页,然后查看Profiler的跟踪:
我们发现TOP (30) 了,并且每次分页执行了2次查询:
1)取得总查询行数,用于DataPager分页
SELECT [GroupBy1].[A1] AS [C1] FROM ( SELECT COUNT(1) AS [A1] FROM [Sales].[Customer] AS [Extent1] ) AS [GroupBy1]
2)分页算法,使用了临时表,算法很通用,不知道性能如何?
SELECT TOP (30) [Extent1].[CustomerID] AS [CustomerID], [Extent1].[TerritoryID] AS [TerritoryID], [Extent1].[AccountNumber] AS [AccountNumber], [Extent1].[CustomerType] AS [CustomerType], [Extent1].[rowguid] AS [rowguid], [Extent1].[ModifiedDate] AS [ModifiedDate] FROM ( SELECT [Extent1].[CustomerID] AS [CustomerID], [Extent1].[TerritoryID] AS [TerritoryID], [Extent1].[AccountNumber] AS [AccountNumber], [Extent1].[CustomerType] AS [CustomerType], [Extent1].[rowguid] AS [rowguid], [Extent1].[ModifiedDate] AS [ModifiedDate], row_number() OVER (ORDER BY [Extent1].[CustomerID] ASC) AS [row_number] FROM [Sales].[Customer] AS [Extent1] ) AS [Extent1] WHERE [Extent1].[row_number] > 30 ORDER BY [Extent1].[CustomerID] ASC