Share via


HOW TO:建立使用 POCO 定義實體的網域服務

本主題說明如何使用 WCF RIA Services 來建立使用單純 CLR 物件 (POCO) 的網域服務。目標是要顯示如何建構一個非常基本、以 POCO 為基礎的 RIA Services 應用程式,特別是說明在程序中的各種不同步驟期間使用RIA Services 工具 (精靈和對話方塊) 時會發生的狀況。從 POCO 提供的資料可用來免除應用程式對後端資料庫做為可攜性或資料安全性之用途或測試之用途的相依性。以 POCO 定義實體所自動產生的用戶端程式碼完全受到 RIA Services 支援,就如同以 Linq to SQL 或 Entity Framework 產生的用戶端程式碼一般。關於資料來源,RIA Services 網域服務其實是無從驗證的,因此這個 POCO 類別稍後可以由存取其他來源 (例如資料庫) 資料的元件所取代,而不需要變更網域服務本身。

除了 WCF RIA Services 之外,此處描述的程序還需要正確安裝並設定數個必要程式,例如 Visual Studio 2010 和 Silverlight 開發人員執行階段與 SDK。但不需要 WCF RIA Services 工具組。在 WCF RIA Services 的必要條件節點中的主題也提供符合這些必要條件的詳細指示。請先按照該處提供的必要程式相關指示進行,然後再進行本使用說明主題,以確保盡可能碰到較少的問題。

建立 RIA Services 方案

  1. 在 Visual Studio 2010 中建立新的 RIA Services 專案,方式是依序選取 [檔案]、[新增] 和 [專案]。

    [新增專案] 對話方塊隨即出現。

  2. 從 [已安裝的範本] 的 [Silverlight] 群組選取 [Silverlight 應用程式] 範本,並將新專案命名為 RIAServicesPocoExample

  3. 按一下 [確定]。

    [新 Silverlight 應用程式] 對話方塊隨即出現。

  4. 選取視窗底部附近的 [啟用 WCF RIA Services] 核取方塊。選取這個方塊會在用戶端專案和伺服器專案間建立 RIA Services 連結。為了啟用此連接,此工具會在用戶端專案加入下列參考:

    • System.ComponentModel.DataAnnotations

    • System.Runtime.Serialization

    • System.ServiceModel.dll

    • System.ServiceModel.DomainServices.Client

    • System.ServiceModel.DomainServices.Client.Web

    • System.ServiceModel.Web.Extensions

    • System.Windows.Browser

  5. 按一下 [確定] 建立方案。

    這個方案包含兩個專案:一個用戶端專案和一個伺服器專案。

    • RIAServicesPocoExample:用戶端專案,包含用來建立展示層的 Silverlight 程式碼。

    • RIAServicesPocoExample.Web:包含中介層程式碼的伺服器專案。

建立網域服務

  1. 以滑鼠右鍵按一下伺服器專案,並選取 [加入] 和 [新增項目]。

  2. 選取類別清單中的 [網頁],然後選取 [DomainService 類別] 範本。

  3. 將類別命名為 SovereignDomainService.cs (或 SovereignDomainService.vb)。

  4. 按一下 [加入]。

    [加入新的 DomainService 類別] 對話方塊隨即出現。

  5. 請確定已核取 [啟用用戶端存取] 方塊。

  6. 請注意,[可用的 DataContext/ObjectContext 類別] 下拉式功能表的唯一可用選項是 [<空的 DomainService 類別>] 實體,請勿選取 [為中繼資料產生關聯的類別] 核取方塊,因為沒有可用來與服務產生關聯的資料內容。

  7. 按一下 [確定]。

    這個精靈會執行多個工作。它會在具有關聯屬性和 using 陳述式的新 SovereignDomainService.cs (或 SovereignDomainService.vb) 檔案中產生空的 SovereignDomainService 類別。此外,也會將四個組件參考加入至服務專案,並將組態項目加入至 Web.config 檔案。

  8. 若要觀察此資料,請開啟 SovereignDomainService.cs (或 SovereignDomainService.vb) 檔案 (如果尚未自動開啟)。請注意,此檔案具有下列特性:

    1. using 陳述式已經加入:

      • using System;

      • using System.Collections.Generic;

      • using System.ComponentModel;

      • using System.ComponentModel.DataAnnotations;

      • using System.Linq;

      • using System.ServiceModel.DomainServices.Hosting;

      • using System.ServiceModel.DomainServices.Server

    2. SovereignDomainService 類別衍生自 DomainService 類別,後者是 RIA Services 架構中的抽象基底類別。也就是 RIA Services 中公開的所有網域服務的基底類別。

    3. SovereignDomainService 類別會以 EnableClientAccessAttribute 屬性標示,表示用戶端層看得到此類別。

  9. 請注意下列參考都已經由精靈加入至服務專案:

    • System.ComponentModel.DataAnnotations

    • System.Runtime.Serialization

    • System.ServiceModel.DomainServices.Hosting

    • System.ServiceModel.DomainServices.Server

  10. 最後,開啟 Web.config 檔案,並檢查由精靈加入的新項目。

    <configuration>
        <system.webServer>
            <modules runAllManagedModulesForAllRequests="true">
                <add name="DomainServiceModule" preCondition="managedHandler"
                    type="System.ServiceModel.DomainServices.Hosting.DomainServiceHttpModule, System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
            </modules>
            <validation validateIntegratedModeConfiguration="false" />
        </system.webServer>
        <system.web>
            <httpModules>
                <add name="DomainServiceModule" type="System.ServiceModel.DomainServices.Hosting.DomainServiceHttpModule, System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
            </httpModules>
            <compilation debug="true" targetFramework="4.0" />
        </system.web>
    
        <system.serviceModel>
            <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
                multipleSiteBindingsEnabled="true" />
        </system.serviceModel>
    </configuration>
    

    除了以 .NET Framework 4.0 為目標的組態項目,每個這些項目都已經由 [加入新的 DomainService 類別] 對話方塊所加入。這些項目可啟用不同的 Internet Information Server (IIS) 裝載和 ASP.NET 選項。

    1. 精靈會在 IIS 7 裝載所需的 <system.webserver> 區段中加入 <modules> 項目。

    2. 精靈會在 IIS 6 裝載所需的 system.web 區段內加入 <httpModules> 項目的 <add> 項目。

    3. RIA Services 網域服務是 Windows Communication Foundation (WCF) 服務,以 ASP.NET 裝載時需要在 ASP.NET 相容性模式中裝載。這項需求不能在程式碼中設定,而必須在 Web.config 檔案中指定。可藉由在 <system.serviceModel> 區段中,將 <ServiceHostingEnvironment> 項目的 aspNetCompatibilityEnabled 屬性設為 true,來啟用 ASP.NET 相容性模式。

加入 POCO 類別

  1. 本程序說明如何對 RIA Services 架構指示 POCO 類別是做為實體型別使用。實體型別提供應用程式資料模型的資料結構,每個實體型別都必須具有唯一實體索引鍵。資料結構是由它所包含的屬性集所指定。藉由指定屬性 (或屬性集) 來提供實體索引鍵,這個屬性必須為每個實體物件提供唯一名稱,以區分相同型別的實體。這通常是透過有些不同的中繼資料所指定。此程序的運作方式是將 [Key] 屬性 (Attribute) 套用至某個屬性 (Property),此屬性 (Attribute) 應用其實就是告知 RIA Services 架構 POCO 類別的執行個體是實體物件。

  2. 開啟 SovereignDomainSevice.cs 檔案。

  3. 在 RIAServicesPocoExample.Web 命名空間的範圍內,截短的 SovereignDomainService 類別之下,加入 Sovereign 類別的下列程式碼:

    
    public class Sovereign
        {
            [Key]
            public int UniqueId { get; set; }
            public string Name { get; set; }
            public string House { get; set; }
            public string Dominion { get; set; }
            public int ReignStart { get; set; }
            public int ReignEnd { get; set; }
            public string Sobriquet { get; set; }
        }
    
  4. 在這個範例中,UniqueId 屬性是針對每個 Sovereign 型別實體物件提供唯一名稱的實體索引鍵。[Key] 屬性定義在 System.ComponentModel.DataAnnotations 組件中,這個組件已加入至伺服器專案,包含此組件之對應命名空間的 using 陳述式也已經加入。實體索引鍵也可以指定於中繼資料檔案或透過其他方式指定,但這是直接在 POCO 類別中指定的便利方式。

  5. Sovereign 類別中加入會傳回 Sovereign 執行個體清單的 FetchSovereigns() 方法:

    
    public List<Sovereign> FetchSovereigns()
            {
                List<Sovereign> sovereignList = new List<Sovereign>
                {
                new Sovereign()
                    {UniqueId = 1, 
                     Name = "John", 
                     House = "Plantagenet", 
                     Dominion = "Angevin Empire", 
                     ReignStart = 1167, 
                     ReignEnd = 1216, 
                     Sobriquet = "Lackland"
                    },
                new Sovereign()
                    {UniqueId = 2, 
                     Name = "Charles", 
                     House = "Stuart", 
                     Dominion = "England, Scotland, & Ireland", 
                     ReignStart = 1625, 
                     ReignEnd = 1649, 
                     Sobriquet = "The Martyr"
                    },
                new Sovereign()
                    {UniqueId = 3, 
                     Name = "William", 
                     House = "Dunkeld", 
                     Dominion = "Scotland", 
                     ReignStart = 1165, 
                     ReignEnd = 1249, 
                     Sobriquet = "The Lion"
                    },   
                new Sovereign()
                    {UniqueId = 4, 
                     Name = "Elizabeth", 
                     House = "Tudor", 
                     Dominion = "England", 
                     ReignStart = 1555, 
                     ReignEnd = 1609, 
                     Sobriquet = "The Virgin Queen"
                    },
                new Sovereign()
                    {UniqueId = 5, 
                     Name = "Ivan", 
                     House = "Vasilyevich", 
                     Dominion = "Russia", 
                     ReignStart = 1533, 
                     ReignEnd = 1584, 
                     Sobriquet = "The Terrible"
                    },
                new Sovereign()
                    {UniqueId = 6, 
                     Name = "Charles", 
                     House = "Valois", 
                     Dominion = "France", 
                     ReignStart = 1380, 
                     ReignEnd = 1422, 
                     Sobriquet = "The Mad"
                    }
                };
            return sovereignList;
            }
    

定義網域服務

  1. 這個程序說明如何在網域服務中建立查詢,用戶端可透過存取此查詢,從 POCO 定義的實體擷取資料。RIA Services 架構需要知道哪些它的方法要在用戶端上做為查詢使用,而且有命名慣例用來達到此目的。RIA Services 架構會將開頭為 Get 且傳回 IEnumerable<EntityType>IQueryable<EntityType> 的方法名稱辨識為查詢。

    Tip提示:
    IQueryable 衍生自 IEnumerableIEnumerable 使用於記憶體中集合 (例如 POCO 定義實體),而在存取基礎或遠端資料來源 (如 SQL 資料庫) 時使用 IQueryable
  2. GetSovereign() 方法加入至 SovereignDomainService 類別。

    
            public IEnumerable<Sovereign> GetSovereigns()
            { 
                Sovereign sovereign = new Sovereign();
                return sovereign.FetchSovereigns();
            }
    
  3. 這會從集合傳回所有王朝實體。但通常,我們只想要傳回實體的子集。為了說明這點,請修改此查詢,從此清單中只傳回中世紀期間 (sovereign.ReignEnd <= 1500) 統治王朝。下列程式碼會執行這項操作:

            public IEnumerable<Sovereign> GetSovereignsByReignEnd(int ReignedBefore)
            {
                Sovereign sovereign = new Sovereign();
                return sovereign.FetchSovereigns().Where<Sovereign>(p => p.ReignEnd <= 1500);
            }
    
  4. 建置 (Ctrl+Shift+B) 此方案,以建立自動產生的用戶端 Proxy 程式碼。

  5. 選取 [方案總管] 中的 [RIAServicesPocoExample] 用戶端專案,按一下視窗頂部的 [顯示所有檔案] 圖示,然後檢查 Generated_Code 資料夾中的 RIAServicesPocoExample.Web.g.cs 檔案。檢查這個檔案中的自動產生程式碼,並注意下列項目:

    • 系統會產生衍生自 WebContextBase 類別的 WebContext 類別,用來管理應用程式內容。

    • 針對網域服務所公開的實體,會產生衍生自 Entity 類別的 Sovereign 類別。用戶端專案中的 Sovereign 實體類別會符合伺服器上的 Sovereign 實體。

    • 系統會產生衍生自 DomainContext 類別的 SovereignDomainContext 類別。此類別有一個名稱為 GetSovereignsByReignEndQuery,且對應到網域服務中建立之查詢方法的方法。

  6. 如需自動程式碼產生的詳細資訊,請參閱產生用戶端程式碼主題。如需如何自訂程式碼產生的詳細資訊,請參閱自訂產生的程式碼主題。

將查詢資料顯示在 Silverlight 用戶端

  1. 開啟 MainPage.xaml。

  2. DataGrid 控制項從左側的 [工具箱] 拖曳到 XAML 檢視的 Grid 項目中。

    從 [工具箱] 拖曳 DataGrid 控制項,會將命名空間的 using System.Windows.Controls 陳述式加入至 MainPage.xaml.cs 檔案,並將 System.Windows.Controls.Data 和 System.Windows.Controls.Data.Input 組件的參考自動加入至用戶端專案。

    Caution注意:
    如果您加入 DataGrid 時,沒有從 [工具箱] 拖曳它,則必須手動將組件參考加入至用戶端專案,並在程式碼後置檔案中手動加入 Using 陳述式。
  3. AutoGeneratedColums 的值變更為 True、將 DataGrid 項目命名為 SovereignGrid,然後調整 HeightWidth,如以下 XAML 所示。

    
    <Grid x:Name="LayoutRoot" Background="White">
         <sdk:DataGrid AutoGenerateColumns="True" 
                       Height="200" 
                       HorizontalAlignment="Left" 
                       Margin="157,86,0,0" 
                       Name="SovereignGrid" 
                       VerticalAlignment="Top"
                       Width="600" />
    </Grid>
    
  4. 開啟 MainPage.xaml.cs 檔案。

  5. 加入 using (C#) 或 Imports (Visual Basic) 兩個陳述式:using RIAServicesPocoExample.Web;using System.ServiceModel.DomainServices.Client;

    RIAServicesPocoExample.Web 命名空間是 RIAServicesPocoExample.Web.g.cs (或 RIAServicesPocoExample.Web.g.vb) 中,包含用戶端專案所產生之程式碼的命名空間。

  6. 若要具現化 SovereignDomainContext,請在 MainPage 類別中加入這行程式碼 private SovereignDomainContext _sovereignContext = new SovereignDomainContext();

  7. 使用 LoadOperation 呼叫 GetSovereignsQuery 方法來擷取客戶實體:LoadOperation<Sovereign> loadOp = this._sovereignContext.Load(this._sovereignContext.GetSovereignsByReignEndQuery(1500));

  8. 使用 SovereignGrid.ItemsSource = loadOp.Entities;,將載入的實體繫結至 DataGrid

    總而言之,MainPage.xaml.cs 檔案現在應該包含下列程式碼:

    //Namespaces added
    using RIAServicesPocoExample.Web;
    using System.ServiceModel.DomainServices.Client;
    
    namespace RIAServicesPocoExample
    {
        public partial class MainPage : UserControl
    
        {
            private SovereignDomainContext _sovereignContext = new SovereignDomainContext();
    
            public MainPage()
            {
    
                InitializeComponent();
    
                  LoadOperation<Sovereign> loadOp = this._sovereignContext.Load(this._sovereignContext.GetSovereignsByReignEndQuery(1500));
                  SovereignGrid.ItemsSource = loadOp.Entities;
            }
        }
    }
    
  9. 執行 (F5) 應用程式。

    您應該會在瀏覽器中看到只顯示中古時代統治王朝 (其統治在公元 1500 年前結束) 的屬性表 (依字母順序)。

安全性

另請參閱

工作

逐步解說:擷取和顯示網域服務的資料

概念

產生用戶端程式碼