Share via


방법: 프로젝트 데이터 소스를 사용하여 데이터 바인딩(WCF Data Services)

WCF Data Services 클라이언트 응용 프로그램에서 생성된 데이터 개체를 기반으로 하는 데이터 소스를 만들 수 있습니다. 서비스 참조 추가 대화 상자를 사용하여 데이터 서비스 참조를 추가하면 생성된 클라이언트 데이터 클래스와 함께 프로젝트 데이터 소스가 만들어집니다. 데이터 서비스에서 노출하는 각 엔터티 집합에 대해 데이터 소스 하나가 만들어집니다. 데이터 소스 창에서 디자이너로 이러한 데이터 소스 항목을 끌어다 놓으면 서비스의 데이터를 표시하는 폼을 만들 수 있습니다. 이러한 항목은 데이터 소스에 바인딩된 컨트롤이 됩니다. 실행 중에 이 데이터 소스는 데이터 서비스 쿼리에서 반환하는 개체로 채워지는 DataServiceCollection 클래스 인스턴스에 바인딩됩니다. 자세한 내용은 컨트롤에 데이터 바인딩(WCF Data Services)을 참조하십시오.

이 항목의 예제에서는 Northwind 샘플 데이터 서비스 및 자동 생성된 클라이언트 데이터 서비스 클래스를 사용합니다. 이 서비스 및 클라이언트 데이터 클래스는 WCF Data Services 퀵 스타트를 완료하면 만들어집니다.

WPF 창에서 프로젝트 데이터 소스를 사용하려면

  1. WPF 프로젝트에서 Northwind 데이터 서비스에 대한 참조를 추가합니다. 자세한 내용은 방법: 데이터 서비스 참조 추가(WCF Data Services)를 참조하십시오.

  2. 데이터 소스 창의 NorthwindEntities 프로젝트 데이터 소스에서 Customers 노드를 확장합니다.

  3. CustomerID 항목을 클릭하고 목록에서 ComboBox를 선택한 다음 Customers 노드에서 디자이너로 CustomerID 항목을 끌어다 놓습니다.

    창에 대한 XAML 파일에 다음 개체 요소가 만들어집니다.

  4. Orders 탐색 속성을 디자이너로 끌어다 놓습니다.

    창에 대한 XAML 파일에 다음 개체 요소가 추가로 만들어집니다.

    • 소스가 customerViewSourcecustomersOrdersViewSource라는 두 번째 CollectionViewSource 요소

    • ordersDataGrid라는 데이터 바인딩된 DataGrid 컨트롤

  5. (선택 사항) Customers 노드에서 디자이너로 추가 항목을 끌어다 놓습니다.

  6. 폼의 코드 페이지를 열고 다음 using 문(Visual Basic에서는 Imports)을 추가합니다.

    using System.Data.Services.Client;
    using NorthwindClient.Northwind;
    
  7. 폼을 정의하는 partial 클래스에서 ObjectContext 인스턴스를 만들고 customerID 상수를 정의하는 다음 코드를 추가합니다.

    Private context As NorthwindEntities
    Private customersViewSource As CollectionViewSource
    Private trackedCustomers As DataServiceCollection(Of Customer)
    Private Const customerCountry As String = "Germany"
    Private Const svcUri As String = "https://localhost:12345/Northwind.svc/"
    
    private NorthwindEntities context;
    private CollectionViewSource customersViewSource;
    private DataServiceCollection<Customer> trackedCustomers;
    private const string customerCountry = "Germany";
    private const string svcUri = "https://localhost:12345/Northwind.svc/";
    
  8. 디자이너에서 창을 선택합니다.

    Ee373840.note(ko-kr,VS.100).gif참고:
    창 안에 있는 콘텐츠를 선택하는 대신 창 자체를 선택해야 합니다.창을 선택하면 속성 창의 위쪽에 있는 이름 텍스트 상자에 창의 이름이 포함되어야 합니다.

  9. 속성 창에서 이벤트 단추를 선택합니다.

  10. 로드됨 이벤트를 찾은 후 이 이벤트 옆에 있는 드롭다운 목록을 두 번 클릭합니다.

    창에 대한 코드 숨김 파일이 열리고 Loaded 이벤트 처리기가 생성됩니다.

  11. 새로 만들어진 Loaded 이벤트 처리기에서 다음 코드를 복사하여 붙여 넣습니다.

    ' Initialize the context for the data service.
    context = New NorthwindEntities(New Uri(svcUri))
    
    ' Create a LINQ query that returns customers with related orders.
    Dim customerQuery = From cust In context.Customers.Expand("Orders") _
                             Where cust.Country = customerCountry _
                             Select cust
    
    ' Create a new collection for binding based on the LINQ query.
    trackedCustomers = New DataServiceCollection(Of Customer)(customerQuery)
    
        try
            ' Get the customersViewSource resource and set the binding to the collection.
        customersViewSource = _
            CType(Me.FindResource("customersViewSource"), CollectionViewSource)
        customersViewSource.Source = trackedCustomers
        customersViewSource.View.MoveCurrentToFirst()
    Catch ex As DataServiceQueryException
        MessageBox.Show("The query could not be completed:\n" + ex.ToString())
    Catch ex As InvalidOperationException
        MessageBox.Show("The following error occurred:\n" + ex.ToString())
    End Try
    
    // Initialize the context for the data service.
    context = new NorthwindEntities(new Uri(svcUri));
    
    // Create a LINQ query that returns customers with related orders.
    var  customerQuery = from cust in context.Customers.Expand("Orders")
                         where cust.Country == customerCountry
                         select cust;
    
    // Create a new collection for binding based on the LINQ query.
    trackedCustomers = new DataServiceCollection<Customer>(customerQuery);
    
    try
    {
        // Get the customersViewSource resource and set the binding to the collection.
        customersViewSource =
            ((CollectionViewSource)(this.FindResource("customersViewSource")));
        customersViewSource.Source = trackedCustomers;
        customersViewSource.View.MoveCurrentToFirst();
    }
    catch (DataServiceQueryException ex)
    {
        MessageBox.Show("The query could not be completed:\n" + ex.ToString());
    }
    catch (InvalidOperationException ex)
    {
        MessageBox.Show("The following error occurred:\n" + ex.ToString());
    }
    
  12. 이 코드에서는 Northwind 데이터 서비스의 관련 Orders 개체와 함께 CustomersIEnumerable을 반환하고 customersViewSource에 바인딩하는 LINQ 쿼리의 실행을 기준으로 Customers 형식에 대해 DataServiceCollection 인스턴스를 만듭니다.

Windows Form에서 프로젝트 데이터 소스를 사용하려면

  1. 데이터 소스 창의 NorthwindEntities 프로젝트 데이터 소스에서 Customers 노드를 확장합니다.

  2. CustomerID 항목을 클릭하고 목록에서 ComboBox를 선택한 다음 Customers 노드에서 디자이너로 CustomerID 항목을 끌어다 놓습니다.

    폼에 다음 컨트롤이 만들어집니다.

    • customersBindingSource라는 BindingSource 인스턴스

    • customersBindingNavigator라는 BindingNavigator 인스턴스. 이 컨트롤은 필요 없으므로 삭제할 수 있습니다.

    • CustomerID라는 데이터 바인딩된 ComboBox

    • Label.

  3. Orders 탐색 속성을 폼으로 끌어다 놓습니다.

  4. 컨트롤의 DataSource 속성이 customersBindingSource로 설정되고 DataMember 속성이 Customers로 설정된 ordersBindingSource 컨트롤이 만들어집니다. ordersDataGridView 데이터 바인딩된 컨트롤도 폼에 만들어지며, 적절한 제목의 레이블 컨트롤이 함께 표시됩니다.

  5. (선택 사항) Customers 노드에서 디자이너로 추가 항목을 끌어다 놓습니다.

  6. 폼의 코드 페이지를 열고 다음 using 문(Visual Basic에서는 Imports)을 추가합니다.

    Imports System.Data.Services.Client
    Imports NorthwindClient.Northwind
    
    using System.Data.Services.Client;
    using NorthwindClient.Northwind;
    
  7. 폼을 정의하는 partial 클래스에서 ObjectContext 인스턴스를 만들고 customerID 상수를 정의하는 다음 코드를 추가합니다.

    Private context As NorthwindEntities
    Private trackedCustomers As DataServiceCollection(Of Customer)
    Private Const customerCountry As String = "Germany"
    Private Const svcUri As String = "http:'localhost:12345/Northwind.svc/"
    
    private NorthwindEntities context;
    private DataServiceCollection<Customer> trackedCustomers;
    private const string customerCountry = "Germany";
    private const string svcUri = "https://localhost:12345/Northwind.svc/";
    
  8. 폼 디자이너에서 폼을 두 번 클릭합니다.

    폼에 대한 코드 페이지가 열리고 폼의 Load 이벤트를 처리하는 메서드가 만들어집니다.

  9. Load 이벤트 처리기에서 다음 코드를 복사하여 붙여 넣습니다.

    ' Initialize the context for the data service.
    context = New NorthwindEntities(New Uri(svcUri))
    Try
        ' Create a LINQ query that returns customers with related orders.
        Dim customerQuery = From cust In context.Customers.Expand("Orders") _
                                Where cust.Country = customerCountry _
                                Select cust
    
        ' Create a new collection for binding based on the LINQ query.
        trackedCustomers = New DataServiceCollection(Of Customer)(customerQuery)
    
        'Bind the Customers combobox to the collection.
        customersComboBox.DisplayMember = "CustomerID"
        customersComboBox.DataSource = trackedCustomers
    Catch ex As DataServiceQueryException
        MessageBox.Show("The query could not be completed:\n" + ex.ToString())
    Catch ex As InvalidOperationException
        MessageBox.Show("The following error occurred:\n" + ex.ToString())
    
    // Initialize the context for the data service.
    context = new NorthwindEntities(new Uri(svcUri));
    try
    {
        // Create a LINQ query that returns customers with related orders.
        var customerQuery = from cust in context.Customers.Expand("Orders")
                            where cust.Country == customerCountry
                            select cust;
    
        // Create a new collection for binding based on the LINQ query.
        trackedCustomers = new DataServiceCollection<Customer>(customerQuery);
    
        //Bind the Customers combobox to the collection.
        customersComboBox.DisplayMember = "CustomerID";
        customersComboBox.DataSource = trackedCustomers;
    }
    catch (DataServiceQueryException ex)
    {
        MessageBox.Show("The query could not be completed:\n" + ex.ToString());
    }
    catch (InvalidOperationException ex)
    {
        MessageBox.Show("The following error occurred:\n" + ex.ToString());
    }
    
  10. 이 코드에서는 Northwind 데이터 서비스에서 CustomersIEnumerable을 반환하고 customersBindingSource에 바인딩하는 DataServiceQuery의 실행을 기준으로 Customers 형식에 대해 DataServiceCollection 인스턴스를 만듭니다.

참고 항목

작업

방법: Windows Presentation Foundation 요소에 데이터 바인딩(WCF Data Services)

기타 리소스

WCF Data Services 클라이언트 라이브러리