다음을 통해 공유


연습: 쿼리 메서드 추가

이 연습에서는 WCF RIA Services에서 데이터 소스를 쿼리하는 메서드를 추가하고 사용자 지정하는 방법을 설명합니다. 이러한 쿼리 메서드를 지정할 때는 프레임워크에서 인식하도록 시그니처를 사용하여 정의해야 합니다. 쿼리 메서드는 QueryAttribute를 적용하여 이 요구 사항을 충족합니다. 필요한 쿼리 시그니처 집합은 크게 단일 형식의 Entity를 항상 반환하는 쿼리와 IEnumerable 또는 IQueryable에서 T 형식의 Entity를 하나 이상 반환할 수 있는 쿼리의 두 가지 범주로 나뉩니다. 허용되는 쿼리 메서드 시그니처에 대한 자세한 내용은 도메인 서비스를 참조하십시오.

새 도메인 서비스 클래스를 만들고 새 도메인 서비스 클래스 추가 대화 상자에서 해당 엔터티를 지정하면 RIA Services 프레임워크에서 서비스에 의해 노출되는 엔터티별로 하나의 단순 쿼리 메서드를 이 클래스에 자동으로 만듭니다. 이 쿼리 메서드는 단순히 엔터티에 대한 모든 레코드를 검색합니다. 이 연습에서는 매개 변수 값 기준 필터링 등의 더 복잡한 시나리오를 수행하는 새 쿼리 메서드를 추가하는 방법에 대해 설명하고, 단일 엔터티를 반환하는 쿼리를 추가하는 방법과 엔터티 컬렉션을 반환하는 쿼리를 추가하는 방법을 보여 줍니다.

필수 구성 요소

RIA Services 설명서에서 제공하는 이 연습 및 다른 연습을 실행하려면 WCF RIA Services 및 WCF RIA Services 도구 키트 외에도 Visual Studio 2010, Silverlight Developer 런타임 및 SDK 등의 몇 가지 필수 구성 요소 프로그램을 올바르게 설치하고 구성해야 합니다. 또한 SQL Server 2008 R2 Express with Advanced Services를 설치하고 구성해야 하며 AdventureWorks OLTP 및 LT 데이터베이스를 설치해야 합니다.

이러한 각 사전 요구 사항을 충족하기 위한 자세한 지침은 WCF RIA Services의 사전 요구 사항 노드의 항목에서 제공합니다. 이 RIA Services 연습을 수행할 때 발생할 수 있는 문제를 최소화하려면 이 연습을 진행하기 전에 여기서 제공하는 지침을 따르십시오.

이 연습에서는 사용자가 연습: RIA Services 솔루션 만들기에서 설명하는 절차를 완료했으며 여기에서 설명하는 절차에서 수정할 솔루션이 만들어져 있다고 가정합니다.

매개 변수를 받아들이고 단일 엔터티를 반환하는 쿼리 메서드를 추가하려면

  1. Customer 테이블의 데이터를 노출하는 연습: RIA Services 솔루션 만들기 항목에서 만든 솔루션을 엽니다.

  2. 서버 프로젝트에서 Customer 테이블의 데이터를 노출하는 CustomerDomainService 도메인 서비스 클래스를 엽니다.

  3. 정수 매개 변수를 받아들이고 고객 ID가 일치하는 Customer 엔터티를 반환하는 query 메서드를 추가합니다.

    단일 엔터티를 반환하는 메서드에 QueryAttribute 특성이 포함되어 있는 경우 IsComposable 속성을 false로 설정해야 합니다. 사용자는 클라이언트에서 추가 쿼리 작업을 지정할 수 없습니다. 쿼리 메서드가 쿼리에 필요한 시그니처와 일치하는 경우 QueryAttribute 특성을 적용할 필요가 없습니다. 엔터티 개체의 단일 인스턴스가 값으로 반환되어야 합니다.

    <Query(IsComposable:=False)>
    Public Function GetCustomersByID(ByVal customerID As Integer) As Customer
        Return Me.ObjectContext.Customers.SingleOrDefault(Function(c) c.CustomerID = customerID)
    End Function
    
    [Query(IsComposable=false)]
    public Customer GetCustomersByID(int customerID)
    {
        return this.ObjectContext.Customers.SingleOrDefault(c => c.CustomerID == customerID);
    }
    

매개 변수를 받아들이고 엔터티 컬렉션을 반환하는 쿼리 메서드를 추가하려면

  1. Customer 테이블의 데이터를 노출하는 도메인 서비스 클래스를 엽니다.

  2. CustomerDomainService 도메인 서비스 클래스에서 문자열 매개 변수를 받아들이고 성이 해당 문자로 시작하는 고객을 반환하는 query 메서드를 추가합니다.

    사용자가 클라이언트에서 추가 쿼리 작업을 제공할 수 있기 때문에 이 메서드에서 IQueryable 개체를 반환할 수 있습니다.

    Public Function GetCustomersByLastNameLetter(ByVal startingLastNameLetter As String) As IQueryable(Of Customer)
        Return Me.ObjectContext.Customers.Where(Function(c) c.LastName.StartsWith(startingLastNameLetter) = True)
    End Function
    
    public IQueryable<Customer> GetCustomersByLastNameLetter(string startingLastNameLetter)
    {
        return this.ObjectContext.Customers.Where(c => c.LastName.StartsWith(startingLastNameLetter) == true);
    }
    

클라이언트 프로젝트에서 query 메서드의 결과를 표시하려면

  1. 클라이언트 프로젝트에서 MainPage.xaml을 엽니다.

  2. 사용자가 ID 또는 성의 첫 글자를 기준으로 고객 레코드를 필터링할 수 있도록 TextBox 컨트롤과 Button 컨트롤을 두 개씩 추가합니다.

    다음 XAML에서는 전체 레이아웃을 기존 DataGrid와 함께 보여 줍니다.

    <UserControl xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"  
        x:Class="RIAServicesExample.MainPage"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="https://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        d:DesignHeight="300" d:DesignWidth="400">
    
        <Grid x:Name="LayoutRoot" Background="White">
            <Grid.ColumnDefinitions>
                <ColumnDefinition></ColumnDefinition>
                <ColumnDefinition></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="25"></RowDefinition>
                <RowDefinition></RowDefinition>
            </Grid.RowDefinitions>
            <StackPanel Orientation="Horizontal" Grid.Row="0" Grid.Column="0">
                <TextBlock Text="search by id: " ></TextBlock>
                <TextBox Name="IDValue" Width="50" ></TextBox>
                <Button Name="IDButton" Click="IDButton_Click" Content="Submit"></Button>
            </StackPanel>
            <StackPanel Orientation="Horizontal" Grid.Row="0" Grid.Column="1">
                <TextBlock Text="search by name: "></TextBlock>
                <TextBox Name="LetterValue" Width="30"></TextBox>
                <Button Name="LetterButton" Click="LetterButton_Click" Content="Submit"></Button>
            </StackPanel>
    
          <data:DataGrid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Name="CustomerGrid"></data:DataGrid>
        </Grid>
    </UserControl>
    
  3. MainPage.xaml(MainPage.xaml.cs 또는 MainPage.xaml.vb)에 대한 코드 숨김 페이지를 엽니다.

  4. 사용자 입력을 기준으로 쿼리 결과를 검색하는 코드를 추가합니다.

    Imports RIAServicesExample.Web
    Imports System.ServiceModel.DomainServices.Client
    
    Partial Public Class MainPage
        Inherits UserControl
        Dim _customerContext As New CustomerDomainContext
    
        Public Sub New()
            InitializeComponent()
        End Sub
    
        Private Sub LetterButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
            IDButton.IsEnabled = False
            LetterButton.IsEnabled = False
            Dim loadOp = Me._customerContext.Load(Me._customerContext.GetCustomersByLastNameLetterQuery(LetterValue.Text), AddressOf CustomerLoadedCallback, Nothing)
            CustomerGrid.ItemsSource = loadOp.Entities
        End Sub
    
        Private Sub IDButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
            IDButton.IsEnabled = False
            LetterButton.IsEnabled = False
            Dim loadOp = Me._customerContext.Load(Me._customerContext.GetCustomersByIDQuery(IDValue.Text), AddressOf CustomerLoadedCallback, Nothing)
            CustomerGrid.ItemsSource = loadOp.Entities
        End Sub
    
        Public Sub CustomerLoadedCallback(ByVal loadOperation As LoadOperation(Of Customer))
            IDButton.IsEnabled = True
            LetterButton.IsEnabled = True
        End Sub
    End Class
    
    using System;
    using System.Windows;
    using System.Windows.Controls;
    using RIAServicesExample.Web;
    using System.ServiceModel.DomainServices.Client;
    
    namespace RIAServicesExample
    {
    
        public partial class MainPage : UserControl
        {
            private CustomerDomainContext _customerContext = new CustomerDomainContext();
    
            public MainPage()
            {
                InitializeComponent();
            }
    
            private void LetterButton_Click(object sender, RoutedEventArgs e)
            {
                IDButton.IsEnabled = false;
                LetterButton.IsEnabled = false;
                LoadOperation<Customer> loadOp = this._customerContext.Load(this._customerContext.GetCustomersByLastNameLetterQuery(LetterValue.Text), CustomerLoadedCallback, null);
                CustomerGrid.ItemsSource = loadOp.Entities;
            }
    
            private void IDButton_Click(object sender, RoutedEventArgs e)
            {
                IDButton.IsEnabled = false;
                LetterButton.IsEnabled = false;
                LoadOperation<Customer> loadOp = this._customerContext.Load(this._customerContext.GetCustomersByIDQuery(int.Parse(IDValue.Text)), CustomerLoadedCallback, null);
                CustomerGrid.ItemsSource = loadOp.Entities;
            }
    
            void CustomerLoadedCallback(LoadOperation<Customer> loadOperation)
            {
                IDButton.IsEnabled = true;
                LetterButton.IsEnabled = true;
            }
        }
    }
    
  5. F5 키를 눌러 응용 프로그램을 실행합니다.

    다음 그림은 응용 프로그램이 실행될 때 표시되는 성을 기준으로 필터링되는 고객 목록을 보여 줍니다.

    RIA_QueryMethods