チュートリアル: ストアド プロシージャを使用したエンティティ型の取得 (Entity Data Model ツール)

このトピックでは、ストアド プロシージャを使用してエンティティ型のコレクションを取得する方法について説明します。 このチュートリアルでは、ADO.NET Entity Data Model デザイナー (エンティティ デザイナー) を使用してストアド プロシージャをインポートし、エンティティ型のコレクションを返す関数インポートを作成します。

ストアド プロシージャを概念モデルに含めると、ストアド プロシージャをアプリケーション コードから呼び出すことができます。 概念モデルに追加されたストアド プロシージャは、関数インポートと呼ばれます。 関数インポートは単純型、複合型、またはエンティティ型のコレクションを返すか、あるいは値を返しません。

Cc716672.note(ja-jp,VS.100).gif注 :
関数インポートが EntityType を返すには、対応するストアド プロシージャによって返される列が、返される EntityType のスカラー プロパティと完全に一致する必要があります。

Entity Data Model ウィザードによってデータベースから .edmx ファイルが生成されるときに、データベース内の各ストアド プロシージャに対応するエントリがストレージ モデルに作成されます。 関数インポートが作成されると、対応するエントリが概念モデルに追加されます。 関数インポートの作成の詳細については、「方法: ストアド プロシージャをインポートする (Entity Data Model ツール)」を参照してください。

前提条件

このチュートリアルを完了するには、CourseManager アプリケーションをビルドする必要があります。 詳細と手順については、「Entity Framework クイック スタート」を参照してください。 このアプリケーションをビルドした後で、GetStudentGrades ストアド プロシージャに基づいて関数インポートを作成し、その概念モデルを変更します。

Cc716672.note(ja-jp,VS.100).gif注 :
このドキュメントのチュートリアルのトピックの多くは CourseManager アプリケーションを開始点としているため、元の CourseManager コードを編集するのではなく、このチュートリアル用に CourseManager アプリケーションのコピーを使用することをお勧めします。

このチュートリアルでは、Visual Studio、.NET Framework、および Visual C# または Visual Basic のプログラミングの基本的なスキルがある読者を想定しています。

関数インポートの作成

この手順では、CourseManager アプリケーションのストレージ モデルに含まれる GetStudentGrades ストアド プロシージャに基づいて関数インポートを作成します。

関数インポートを作成するには

  1. Visual Studio で CourseManager ソリューションを開きます。

  2. ソリューション エクスプローラーで、School.edmx ファイルをダブルクリックします。

    ADO.NET Entity Data Model デザイナー (エンティティ デザイナー) で School.edmx ファイルが開き、[モデル ブラウザー] ウィンドウが開きます。

  3. [モデル ブラウザー] ウィンドウで [EntityContainer: SchoolEntities] ノードを展開します。

    ツリー ビューに [エンティティ セット][アソシエーション セット]、および [関数インポート] の各フォルダーが表示されます。

  4. [関数インポート] を右クリックし、[関数インポートの追加] をクリックします。

    [Add Function Import] ダイアログ ボックスが表示されます。

  5. [ストアド プロシージャ名] ボックスの一覧で [GetStudentGrades] をクリックします。

  6. [関数インポート名] ボックスに「GetStudentGrades」と入力します。

  7. 戻り値として [エンティティ] をクリックし、対応するドロップダウン リストで [StudentGrade] をクリックします。

    Cc716672.note(ja-jp,VS.100).gif注 :
    GetStudentGrades ストアド プロシージャによって返される列 (EnrollementIDStudentIDCourseID、および Grade) は StudentGrade エンティティ型のスカラー プロパティと正確に一致するので、戻り値の型を StudentGrade に設定できます。

  8. [OK] をクリックします。

    GetStudentGrades Function Import が概念モデルに追加されます。

ユーザー インターフェイスの構築

この手順では、選択した学生の成績を表示できるように、CourseManager アプリケーションのユーザー インターフェイスに新しいフォームを追加します。

ユーザー インターフェイスを構築するには

  1. ソリューション エクスプローラーで [CourseManager] プロジェクトを右クリックし、[追加] をポイントして [新しい項目] をクリックします。

    [新しい項目の追加] ダイアログ ボックスが表示されます。

  2. [Windows フォーム] を選択し、フォーム名を GradeViewer.vb または GradeViewer.cs に設定して、[追加] をクリックします。

    新しいフォームがプロジェクトに追加され、フォーム デザイナーで開かれます。 フォーム名が GradeViewer に、テキストが GradeViewer に設定されます。

  3. ComboBox コントロールをツールボックスからフォームにドラッグし、[プロパティ] ウィンドウで [名前]studentList に設定します。

  4. DataGridView コントロールをツールボックスからフォームにドラッグし、[プロパティ] ウィンドウで [名前]gradeGridView に設定します。

  5. ソリューション エクスプローラーCourseViewer.vb ファイルまたは CourseViewer.cs ファイルをダブルクリックします。

    フォーム デザイナーでファイルが開きます。

  6. フォームに Button コントロールをドラッグします。 [名前]viewGrades に、[テキスト]View Grades に設定します。

  7. viewGrades Button コントロールをダブルクリックします。

    viewGrades_Click イベント ハンドラーが分離コード ファイルに追加されます。

  8. viewGrades_Click イベント ハンドラーに次のコードを追加します。

    Dim gradeViewer As New GradeViewer()
    gradeViewer.Visible = True
    
    GradeViewer gradeViewer = new GradeViewer();
    gradeViewer.Visible = true;
    

ユーザー インターフェイスが完成しました。

ストアド プロシージャを使用したエンティティ型の取得

この手順では、以前 GetStudentGrades ストアド プロシージャから作成した関数インポートを実行するコードを追加します。 このコードは、返された EntityType コレクションを DataGridView コントロールにバインドします。 オブジェクトをコントロールにバインドする方法の詳細については、「Binding Objects to Controls (Entity Framework)」を参照してください。

ストアド プロシージャを使用してエンティティ型を取得するには

  1. フォーム デザイナーで GradeViewer フォームが開いた状態で、フォームの本文をダブルクリックします。

    GradeViewer フォームの分離コード ファイルが開きます。

  2. 次の using (C#) ステートメントまたは Imports (Visual Basic) ステートメントを追加します。

    Imports System.Data.Objects
    Imports System.Data.Objects.DataClasses
    
    using System.Data.Objects;
    using System.Data.Objects.DataClasses;
    
  3. オブジェクト コンテキストを表すプロパティを GradeViewer クラスに追加します。

    ' Create an ObjectContext instance based on SchoolEntity.
    Private schoolContext As SchoolEntities
    
    // Create an ObjectContext instance based on SchoolEntity.
    private SchoolEntities schoolContext;
    
  4. GradeViewer_Load イベント ハンドラーで、次のコードを追加します。 このコードは、オブジェクト コンテキストを初期化し、ComboBox コントロールのデータ ソースを、EnrollmentDatenull ではないすべての Person 型を返すクエリに設定します。

    ' Initialize schoolContext.
    schoolContext = New SchoolEntities()
    
    ' Define the query to retrieve students.
    Dim studentQuery As ObjectQuery(Of Person) = schoolContext _
        .People.Where("it.EnrollmentDate is not null") _
        .OrderBy("it.LastName")
    
    ' Execute and bind the studentList control to the query.
    studentList.DataSource = studentQuery _
        .Execute(MergeOption.OverwriteChanges)
    studentList.DisplayMember = "LastName"
    
    schoolContext = new SchoolEntities();
    
    // Define the query to retrieve students.
    ObjectQuery<Person> studentQuery = schoolContext.People
        .Where("it.EnrollmentDate is not null")
        .OrderBy("it.LastName");
    
    // Execute and bind the studentList control to the query.
    studentList.DataSource = studentQuery
        .Execute(MergeOption.OverwriteChanges);
    studentList.DisplayMember = "LastName";
    
  5. GradeViewer フォームのデザイン ビューに戻り、studentList ComboBox コントロールをダブルクリックします。

    studentList_SelectedIndexChanged イベント ハンドラーが分離コード ファイルに追加されます。

  6. studentList_SelectedIndexChanged イベント ハンドラーに次のコードを追加します。 このコードは、GetStudentGrades Function Import を実行し、ドロップダウン リストから新しい学生が選択されると DataGridView コントロールに結果をバインドします。

    ' Get the selected student so we can use the
    ' PersonID in the function import call.
    Dim currentStudent As Person = CType(Me.studentList _
        .SelectedItem(), Person)
    
    ' Set the data source for the gradeGridView
    ' to the results returned by the GetStudentGrades
    ' Function Import.
    gradeGridView.DataSource = schoolContext _
        .GetStudentGrades(currentStudent.PersonID)
    gradeGridView.Columns("Course").Visible = False
    gradeGridView.Columns("StudentID").Visible = False
    gradeGridView.Columns("Person").Visible = False
    gradeGridView.Columns("EnrollmentID").Visible = False
    gradeGridView.AllowUserToAddRows = False
    gradeGridView.AllowUserToDeleteRows = False
    
    // Get the selected student so we can use the
    // PersonID in the function import call.
    Person currentStudent = (Person)this.studentList
        .SelectedItem;
    
    // Set the data source for the gradeGridView
    // to the results returned by the GetStudentGrades
    // Function Import.
    gradeGridView.DataSource = schoolContext
        .GetStudentGrades(currentStudent.PersonID);
    gradeGridView.Columns["Course"].Visible = false;
    gradeGridView.Columns["StudentID"].Visible = false;
    gradeGridView.Columns["Person"].Visible = false;
    gradeGridView.Columns["EnrollmentID"].Visible = false;
    gradeGridView.AllowUserToAddRows = false;
    gradeGridView.AllowUserToDeleteRows = false;
    

Ctrl キーを押しながら F5 キーを押してアプリケーションを実行します。 これで、[View Grades] をクリックして Grade Viewer フォームのドロップダウン リストから学生を選択すると、学生の成績の情報を表示できるようになりました。

コード リスト

このセクションでは、GradeViewer フォームの分離コード ファイルの最終バージョンを示します。

Imports System.Data.Objects
Imports System.Data.Objects.DataClasses
Public Class GradeViewer
    ' Create an ObjectContext instance based on SchoolEntity.
    Private schoolContext As SchoolEntities

    Private Sub GradeViewer_Load(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles MyBase.Load
        ' Initialize schoolContext.
        schoolContext = New SchoolEntities()

        ' Define the query to retrieve students.
        Dim studentQuery As ObjectQuery(Of Person) = schoolContext _
            .People.Where("it.EnrollmentDate is not null") _
            .OrderBy("it.LastName")

        ' Execute and bind the studentList control to the query.
        studentList.DataSource = studentQuery _
            .Execute(MergeOption.OverwriteChanges)
        studentList.DisplayMember = "LastName"
    End Sub

    Private Sub studentList_SelectedIndexChanged(ByVal sender As  _
        System.Object, ByVal e As System.EventArgs) Handles _
        studentList.SelectedIndexChanged
        ' Get the selected student so we can use the
        ' PersonID in the function import call.
        Dim currentStudent As Person = CType(Me.studentList _
            .SelectedItem(), Person)

        ' Set the data source for the gradeGridView
        ' to the results returned by the GetStudentGrades
        ' Function Import.
        gradeGridView.DataSource = schoolContext _
            .GetStudentGrades(currentStudent.PersonID)
        gradeGridView.Columns("Course").Visible = False
        gradeGridView.Columns("StudentID").Visible = False
        gradeGridView.Columns("Person").Visible = False
        gradeGridView.Columns("EnrollmentID").Visible = False
        gradeGridView.AllowUserToAddRows = False
        gradeGridView.AllowUserToDeleteRows = False
    End Sub
End Class
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Objects;
using System.Data.Objects.DataClasses;

namespace CourseManager
{
    public partial class GradeViewer : Form
    {
        // Create an ObjectContext instance based on SchoolEntity.
        private SchoolEntities schoolContext;

        public GradeViewer()
        {
            InitializeComponent();
        }

        private void GradeViewer_Load(object sender, EventArgs e)
        {
            schoolContext = new SchoolEntities();

            // Define the query to retrieve students.
            ObjectQuery<Person> studentQuery = schoolContext.People
                .Where("it.EnrollmentDate is not null")
                .OrderBy("it.LastName");

            // Execute and bind the studentList control to the query.
            studentList.DataSource = studentQuery
                .Execute(MergeOption.OverwriteChanges);
            studentList.DisplayMember = "LastName";
        }

        private void studentList_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Get the selected student so we can use the
            // PersonID in the function import call.
            Person currentStudent = (Person)this.studentList
                .SelectedItem;

            // Set the data source for the gradeGridView
            // to the results returned by the GetStudentGrades
            // Function Import.
            gradeGridView.DataSource = schoolContext
                .GetStudentGrades(currentStudent.PersonID);
            gradeGridView.Columns["Course"].Visible = false;
            gradeGridView.Columns["StudentID"].Visible = false;
            gradeGridView.Columns["Person"].Visible = false;
            gradeGridView.Columns["EnrollmentID"].Visible = false;
            gradeGridView.AllowUserToAddRows = false;
            gradeGridView.AllowUserToDeleteRows = false;
        }
    }
}

次の手順

ここでは、エンティティ型のコレクションを取得する関数インポートを作成しました。 Entity Framework を使用するアプリケーションを構築する方法の詳細については、「ADO.NET Entity Framework」を参照してください。

参照

その他のリソース

Entity Data Model ツールのシナリオ
Entity Data Model ツールのタスク