컨트롤에 개체 바인딩(Entity Framework)

Entity Framework 를 사용하여 ComboBox, ListView, DataGridView 등의 컨트롤을 ObjectQuery를 실행할 때 반환되는 ObjectResultEntityCollection에 바인딩할 수 있습니다. 두 Entity Framework 클래스는 데이터 바인딩을 위해 IListSource 인터페이스를 구현합니다. Entity Framework 도구에서 생성하는 엔터티 형식은 INotifyPropertyChanged를 구현합니다. 따라서 개체 속성 및 컨트롤 사이에 양방향 데이터 바인딩을 사용하므로 컨트롤을 업데이트하면 바인딩된 개체의 속성으로 전달됩니다.

개체를 Windows Form 컨트롤에 바인딩하려면 컨트롤의 DataSource 속성을 EntityCollection 또는 ObjectQuery 개체에서 Execute 메서드를 호출할 때 반환되는 ObjectResult로 설정합니다. 다음 예제에서는 EntityCollectionDataGridView 컨트롤에 바인딩합니다.

// Bind the items for this order to the DataGridView.
lineItemsDataGrid.DataSource = order.SalesOrderDetails;

자세한 내용은 방법: Windows Form 컨트롤에 개체 바인딩(Entity Framework)을 참조하십시오.

Visual Studio 응용 프로그램에서 개체를 기반으로 하는 데이터 소스를 만들 수 있습니다. 엔터티 형식을 프로젝트의 데이터 소스로 정의한 후 데이터 소스 창의 항목을 폼으로 끌어 Entity Framework 데이터를 표시하는 폼을 만들 수 있습니다. 이러한 항목은 데이터 소스에 바인딩된 폼의 컨트롤이 됩니다. 자세한 내용은 Data Sources Window을 참조하십시오. 런타임에 형식화된 ObjectQuery의 결과를 데이터 소스에 사용되는 BindingSourceDataSource 속성에 할당합니다. 그러면 컨트롤의 쿼리에서 반환된 개체의 속성이 표시됩니다. 직접 데이터 바인딩과 마찬가지로 SaveChanges 메서드를 호출할 때 컨트롤 값의 업데이트를 데이터 소스에 적용합니다. 자세한 내용은 방법: 프로젝트 데이터 소스로 개체 추가(Entity Framework)를 참조하십시오.

개체를 WPF(Windows Presentation Foundation) 컨트롤에 바인딩하려면 컨트롤의 DataContext 속성을 EntityCollection 또는 ObjectQuery 개체에서 Execute 메서드를 호출할 때 반환되는 ObjectResult로 설정합니다. ItemsSource 속성을 사용하여 컨트롤에 대한 개체 소스를 설정합니다. 탐색 속성에서 반환된 관련 개체에 컨트롤을 바인딩하는 경우 ItemsSource 속성에 대해 정의된 바인딩에 경로를 포함합니다. 이 경로는 부모 컨트롤의 DataContext 속성에 설정된 루트 개체에 상대적입니다. 다음 예제에서는 Grid 컨트롤의 DataContext 속성을 설정하여 컨트롤을 ObjectResult에 바인딩합니다.

' Execute the query and bind the result to the OrderItems control.
Me.orderItemsGrid.DataContext = CType(query, ObjectQuery).Execute(MergeOption.AppendOnly)
// Execute the query and bind the result to the OrderItems control.
this.orderItemsGrid.DataContext = ((ObjectQuery)query).Execute(MergeOption.AppendOnly);

다음 예제에서는 자식 ListViewComboBox 컨트롤의 XAML 바인딩 정의를 보여 줍니다.

<ComboBox DisplayMemberPath="SalesOrderID" ItemsSource="{Binding}"
          IsSynchronizedWithCurrentItem="true" 
          Height="23" Margin="122,12,198,0" Name="comboBoxOrder" VerticalAlignment="Top"/>
<ListView ItemsSource="{Binding Path=SalesOrderDetails}" Name="listViewItems" Margin="34,46,34,50">
    <ListView.View>
        <GridView AllowsColumnReorder="False" ColumnHeaderToolTip="Line Items">
            <GridViewColumn DisplayMemberBinding="{Binding Path=ProductID}" 
                Header="Product" Width="50"/>
            <GridViewColumn DisplayMemberBinding="{Binding Path=OrderQty}" 
                Header="Quantity" Width="50"/>
            <GridViewColumn DisplayMemberBinding="{Binding Path=UnitPrice}" 
                Header="Cost" Width="50"/>
            <GridViewColumn DisplayMemberBinding="{Binding Path=LineTotal}" 
                Header="Line Total" Width="80"/>
        </GridView>
    </ListView.View>
</ListView>

자세한 내용은 방법: Windows Presentation Foundation 컨트롤에 개체 바인딩(Entity Framework)을 참조하십시오.

Entity Framework 에는 EntityDataSource 웹 서버 컨트롤이 포함됩니다. 이 ASP.NET 데이터 소스 컨트롤을 사용하여 개체 쿼리의 결과를 ASP.NET 웹 페이지의 컨트롤에 바인딩할 수 있습니다. 자세한 내용은 EntityDataSource 컨트롤 예제를 참조하십시오.

개체를 컨트롤에 바인딩할 때는 다음 사항을 고려해야 합니다.

  • 컨트롤을 ObjectQuery에 직접 바인딩하지 않는 것이 좋습니다. 대신, 컨트롤을 Execute 메서드의 결과에 바인딩하십시오. 이런 방식으로 바인딩하면 바인딩 중에 쿼리가 여러 번 실행되지 않습니다.

    Bb738469.note(ko-kr,VS.100).gif참고:
    LINQ 쿼리로 작업하려면 쿼리의 결과를 ObjectQuery로 캐스팅하고 Execute 메서드를 호출하는 것이 좋습니다.

    다음 예제에서는 SalesOrderHeader 형식의 ObjectQuery를 실행할 때 반환되는 ObjectResultComboBox를 바인딩합니다.

    // Create a query for orders that includes line items.
    ObjectQuery<SalesOrderHeader> orderQuery = context.SalesOrderHeaders
        .Where("it.CustomerID = @customerId", 
        new ObjectParameter("customerId", customerId))
        .Include("SalesOrderDetails");
    
    // Display the PO number in the combo box.
    this.ordersListBox.DisplayMember = "PurchaseOrderNumber";
    
    // Bind the combo box to the ObjectResult of SalesOrderHeader 
    // that is returned when the query is executed.
    this.ordersListBox.DataSource = orderQuery.Execute(MergeOption.AppendOnly);
    
  • 데이터 소스가 최신 상태인지 확인하려면 Execute 메서드를 사용하여 쿼리를 다시 실행해야 할 수도 있습니다. 그러면 컨트롤이 새 ObjectResult에 바인딩됩니다. 다음의 경우 이 작업을 수행하여 개체 데이터가 최신 상태인지 확인해야 합니다.

    • 바인딩된 컨트롤 외부에서 동일한 ObjectContext를 변경하는 경우

    • 데이터 소스의 데이터를 변경하는 경우

    • NoTracking 옵션을 사용하여 개체가 반환된 경우

  • 데이터 바인딩이 발생한 후 컨트롤에서 개별 엔터티 개체에 액세스할 수 있습니다. 그러나 바인딩된 컨트롤에서 컬렉션에 액세스할 수는 없습니다. 자세한 내용은 방법: Windows Form 컨트롤에 개체 바인딩(Entity Framework)을 참조하십시오.

  • EntityCollectionIListSource를 구현하기 때문에 컨트롤에 바인딩할 수 있습니다. 그러나 EntityCollection에서 OfType 메서드를 실행하여 파생 형식의 개체 컬렉션을 반환하는 경우 반환된 IEnumerable을 직접 컨트롤에 바인딩할 수 없습니다. EntityCollection에서 얻은 파생 형식의 개체 컬렉션에 컨트롤을 바인딩하려면 대신 CreateSourceQuery 메서드를 사용하여 기본 EntityCollection을 정의하는 ObjectQuery를 가져옵니다. 다음 예제와 같이 ObjectQueryOfType 메서드에서 반환된 ObjectQuery 실행에 컨트롤을 바인딩할 수 있습니다.

    // Bind the data grid to the result of the execution of the ObjectQuery 
    // that returns only the online courses for the selected department.
    dataGridViewCourses.DataSource =
        selectedDepartment.Courses.CreateSourceQuery()
        .OfType<OnlineCourse>().Execute(MergeOption.AppendOnly);
    

    자세한 내용은 방법: 파생 형식에 컨트롤 바인딩(Entity Framework)을 참조하십시오.

단원 내용

방법: Windows Form 컨트롤에 개체 바인딩(Entity Framework)

방법: Windows Presentation Foundation 컨트롤에 개체 바인딩(Entity Framework)

방법: 파생 형식에 컨트롤 바인딩(Entity Framework)

방법: 프로젝트 데이터 소스로 개체 추가(Entity Framework)

참고 항목

개념

개체 사용(Entity Framework)

기타 리소스

Walkthrough: Creating the Class Schedule Web Application