天天看點

WCF RIA Services 用戶端、服務端的處理方法和例子

1. 首先Project Link到服務端項目,Build服務端項目是在用戶端項目的Generated_Code和其他一些目錄下會生成相關的代碼

2. 使用代碼或XAML(DomainDataSource )通路服務

xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" xmlns:riaControls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.DomainServices">

    <Grid x:Name="LayoutRoot">

           <Grid.RowDefinitions>

                  <RowDefinition/>

           </Grid.RowDefinitions>

            <riaControls:DomainDataSource Name="DataSource" AutoLoad="True"

                                QueryName="GetCustomers">

                  <riaControls:DomainDataSource.DomainContext>

                        <domain:NorthWindContext/>

                  </riaControls:DomainDataSource.DomainContext>

           </riaControls:DomainDataSource>

<sdk:DataGrid Name="dataGrid1" Grid.Row="0" ItemsSource="{Binding ElementName=DataSource, Path=Data}" />

           <sdk:DataGrid Name="dataGrid2" Grid.Row="1"/>

    </Grid>

檢視HTTP協定可以看到發到服務端的請求如下:

GET /ClientBin/RIA-Web-Services-NorthWindService.svc/binary/GetCustomers

GET /ClientBin/RIA-Web-Services-NorthWindService.svc/binary/GetCustomers?$where=(it.City%253d%253d%2522london%2522)&$orderby=it.CustomerID HTTP/1.1

可以看到整個的方式和WCF Data Service基本一緻

注:DomainDataSource包含在 System.Windows.Controls.DomainServices元件中

服務端服務類中的方法遵循如下的約定

方法字首

标注屬性

說明

(Any)

[Query()]

A method that returns data without any side effects. The usual approach is to prefix with Get, but any prefix is fine as long as the function returns an instance of an entity T, an IEnumerable<T>, or an IQueryable<T>.

Insert, Add, Create

[Insert()]

An operation that inserts a single entity into the data store. The method takes the entity as a parameter.

Update, Change,

Modify

[Update()]

An operation that updates a single entity in the data store. The method takes the entity as a parameter.

Delete, Remove

[Delete()]

An operation that deletes an entity in the data store. The method takes the entity as a parameter.

[Invoke()]

A business method that must be executed without tracking or deferred execution. It may or may not have side effects. Use only when one of the other method types can’t be used.

[Update(UsingCustomMethod=true)]

标注UsingCustomMethod=true屬性,執行特定更新的操作,如需要手動進行級聯更新的情況

參數是實體類,在SubmitChanges調用時,自動調用這個更新實體的函數

-

[Ignore()]

方法盡管符合約定如UpdateEmployee,但不要生成用戶端的樁

以上的說明都是在服務端類中可以編寫的方法,在這個類中你可以進行業務邏輯的驗證和處理,資料的更新等等各種操作.

運作效果如下圖:

WCF RIA Services 用戶端、服務端的處理方法和例子

包括了資料的清單顯示,資料的編輯和Domain Service方法,具體有:

DomainDataSource 的使用:過濾、分頁、排序、分組等

DataForm 和DomainDataSource結合實作資料的增删改

手工的調用服務端方法

Sliverlight中,如果對于比較大的應用,為了更清晰的分層,可以考慮使用MVVP模式

特别注意:Sliverlight中調用服務端的代碼,很多情況下都是異步的[具體的原因和浏覽器有關,詳細解釋參考MSDN],是以使用方法傳回的結果需要注意