다음을 통해 공유


.NET Framework 클라이언트 응용 프로그램 만들기(WCF Data Services 퀵 스타트)

이 작업은 WCF Data Services 퀵 스타트의 마지막 작업입니다. 이 작업에서는 솔루션에 콘솔 응용 프로그램을 추가하고, 이 새 클라이언트 응용 프로그램에 Open Data Protocol(OData) 피드에 대한 참조를 추가하고, 생성된 클라이언트 데이터 서비스 클래스와 클라이언트 라이브러리를 사용하여 클라이언트 응용 프로그램에서 OData 피드에 액세스합니다.

Dd728278.note(ko-kr,VS.100).gif참고:
데이터 피드에 액세스하기 위해 .NET Framework 기반 클라이언트 응용 프로그램이 필요하지는 않습니다.OData 피드를 사용하는 모든 응용 프로그램 구성 요소에서 데이터 서비스에 액세스할 수 있습니다.자세한 내용은 클라이언트 응용 프로그램에서 데이터 서비스 사용(WCF Data Services)을 참조하십시오.

Visual Studio를 사용하여 클라이언트 응용 프로그램을 만들려면

  1. 솔루션 탐색기에서 솔루션을 마우스 오른쪽 단추로 클릭하고 추가, 새 프로젝트를 차례로 클릭합니다.

  2. 프로젝트 형식에서 Windows를 클릭하고 템플릿 창에서 WPF 응용 프로그램을 선택합니다.

  3. 프로젝트 이름으로 NorthwindClient를 입력하고 확인을 클릭합니다.

  4. Window1.xaml 파일을 열고 XAML 코드를 다음 코드로 바꿉니다.

        <Window x:Class="MainWindow"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        Title="Northwind Orders" Height="335" Width="425" 
            Name="OrdersWindow" Loaded="Window1_Loaded">
        <Grid Name="orderItemsGrid">
            <ComboBox DisplayMemberPath="OrderID" ItemsSource="{Binding}"
                      IsSynchronizedWithCurrentItem="true" 
                      Height="23" Margin="92,12,198,0" Name="comboBoxOrder" VerticalAlignment="Top"/>
            <DataGrid ItemsSource="{Binding Path=Order_Details}"  
                      CanUserAddRows="False" CanUserDeleteRows="False"  
                      Name="orderItemsDataGrid" Margin="34,46,34,50"
                      AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn  Header="Product" Binding="{Binding ProductID, Mode=OneWay}" />
                    <DataGridTextColumn  Header="Quantity" Binding="{Binding Quantity, Mode=TwoWay}" />
                    <DataGridTextColumn  Header="Price" Binding="{Binding UnitPrice, Mode=TwoWay}" />
                    <DataGridTextColumn  Header="Discount" Binding="{Binding Discount, Mode=TwoWay}" />                
                </DataGrid.Columns>     
            </DataGrid>
            <Label Height="28" Margin="34,12,0,0" Name="orderLabel" VerticalAlignment="Top" 
                   HorizontalAlignment="Left" Width="65">Order:</Label>
            <StackPanel Name="Buttons" Orientation="Horizontal" HorizontalAlignment="Right" 
                        Height="40" Margin="0,257,22,0">
                <Button Height="23" HorizontalAlignment="Right" Margin="0,0,12,12" 
                    Name="buttonSave" VerticalAlignment="Bottom" Width="75" 
                        Click="buttonSaveChanges_Click">Save Changes
                </Button>
                <Button Height="23" Margin="0,0,12,12" 
                    Name="buttonClose" VerticalAlignment="Bottom" Width="75" 
                        Click="buttonClose_Click">Close</Button>
            </StackPanel>
        </Grid>
    </Window>
    

프로젝트에 데이터 서비스 참조를 추가하려면

  1. NorthwindClient 프로젝트를 마우스 오른쪽 단추로 클릭하고 서비스 참조 추가, 검색을 차례로 클릭합니다.

    첫 번째 작업에서 만든 Northwind 데이터 서비스가 표시됩니다.

  2. 네임스페이스 텍스트 상자에 Northwind를 입력하고 확인을 클릭합니다.

    데이터 서비스 리소스에 개체로 액세스하고 상호 작용하는 데 사용되는 데이터 클래스가 포함된 새 코드 파일이 프로젝트에 추가됩니다. 데이터 클래스는 NorthwindClient.Northwind 네임스페이스에 만들어집니다.

WPF 응용 프로그램에서 데이터 서비스 데이터에 액세스하려면

  1. 솔루션 탐색기NorthwindClient에서 프로젝트를 마우스 오른쪽 단추로 클릭하고 참조 추가를 클릭합니다.

  2. 참조 추가 대화 상자에서 .NET 탭을 클릭하고 System.Data.Services.Client.dll 어셈블리를 선택한 다음 확인을 클릭합니다. 솔루션 탐색기NorthwindClient에서 Window1.xaml 파일의 코드 페이지를 열고 다음 using 문(Visual Basic에서는 Imports)을 추가합니다.

    Imports System.Data.Services.Client
    Imports NorthwindClient.Northwind
    
    using System.Data.Services.Client;
    using NorthwindClient.Northwind;
    
  3. 해당 데이터 서비스를 쿼리하고 결과를 DataServiceCollection에 바인딩하는 다음 코드를 Window1 클래스에 삽입합니다.

    Dd728278.note(ko-kr,VS.100).gif참고:
    Northwind 데이터 서비스 인스턴스를 호스팅하는 서버 및 포트로 호스트 이름 localhost:12345를 바꾸어야 합니다.

    Private context As NorthwindEntities
    Private customerId As String = "ALFKI"
    
    ' Replace the host server and port number with the values 
    ' for the test server hosting your Northwind data service instance.
    Private svcUri As Uri = New Uri("https://localhost:12345/Northwind.svc")
    
    Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Try
            ' Instantiate the DataServiceContext.
            context = New NorthwindEntities(svcUri)
    
            ' Define a LINQ query that returns Orders and 
            ' Order_Details for a specific customer.
            Dim ordersQuery = From o In context.Orders.Expand("Order_Details") _
                                  Where o.Customer.CustomerID = customerId _
                                  Select o
    
            ' Create an DataServiceCollection(Of T) based on
            ' execution of the LINQ query for Orders.
            Dim customerOrders As DataServiceCollection(Of Order) = New  _
                DataServiceCollection(Of Order)(ordersQuery)
    
            ' Make the DataServiceCollection<T> the binding source for the Grid.
            Me.orderItemsGrid.DataContext = customerOrders
        Catch ex As Exception
            MessageBox.Show(ex.ToString())
        End Try
    End Sub
    
    private NorthwindEntities context;
    private string customerId = "ALFKI";
    
    // Replace the host server and port number with the values 
    // for the test server hosting your Northwind data service instance.
    private Uri svcUri = new Uri("https://localhost:12345/Northwind.svc");
    
    private void Window1_Loaded(object sender, RoutedEventArgs e)
    {
        try
        {
            // Instantiate the DataServiceContext.
            context = new NorthwindEntities(svcUri);
    
            // Define a LINQ query that returns Orders and 
            // Order_Details for a specific customer.
            var ordersQuery = from o in context.Orders.Expand("Order_Details")
                              where o.Customer.CustomerID == customerId
                              select o;
    
            // Create an DataServiceCollection<T> based on 
            // execution of the LINQ query for Orders.
            DataServiceCollection<Order> customerOrders = new
                DataServiceCollection<Order>(ordersQuery);
    
            // Make the DataServiceCollection<T> the binding source for the Grid.
            this.orderItemsGrid.DataContext = customerOrders;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
    
  4. 변경 내용을 저장하는 다음 코드를 Window1 클래스에 삽입합니다.

    Private Sub buttonSaveChanges_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Try
            ' Save changes made to objects tracked by the context.
            context.SaveChanges()
        Catch ex As DataServiceRequestException
            MessageBox.Show(ex.ToString())
        End Try
    End Sub
    Private Sub buttonClose_Click(ByVal sender As Object, ByVal a As RoutedEventArgs)
        Me.Close()
    End Sub
    
    private void buttonSaveChanges_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            // Save changes made to objects tracked by the context.
            context.SaveChanges();
        }
        catch (DataServiceRequestException ex)
        {
            MessageBox.Show(ex.ToString());
    
        }
    }
    private void buttonClose_Click(object sender, RoutedEventArgs e)
    {
        this.Close();
    }
    

NorthwindClient 응용 프로그램을 빌드 및 실행하려면

  1. 솔루션 탐색기에서 NorthwindClient 프로젝트를 마우스 오른쪽 단추로 클릭하고 시작 프로젝트로 설정을 선택합니다.

  2. F5 키를 눌러 응용 프로그램을 시작합니다.

    솔루션이 빌드되고 클라이언트 응용 프로그램이 시작됩니다. 서비스에서 데이터가 요청되고 콘솔에 표시됩니다.

  3. 데이터 표의 Quantity 열에 있는 값을 편집한 다음 저장을 클릭합니다.

    변경 내용이 데이터 서비스에 저장됩니다.

    Dd728278.note(ko-kr,VS.100).gif참고:
    이 버전의 NorthwindClient 응용 프로그램은 엔터티의 추가와 삭제를 지원하지 않습니다.

다음 단계

샘플 Northwind OData 피드에 액세스하는 클라이언트 응용 프로그램을 성공적으로 만들었으며 WCF Data Services 퀵 스타트도 완료했습니다. .NET Framework 응용 프로그램에서 OData 피드에 액세스하는 방법은 WCF Data Services 클라이언트 라이브러리을 참조하십시오.

참고 항목

개념

WCF Data Services 시작
WCF Data Services 리소스