次の方法で共有


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

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

ストアド プロシージャを Entity Data Model (EDM) に含めると、ストアド プロシージャをアプリケーション コードから呼び出すことができます。概念モデルに追加されたストアド プロシージャは、Function Import と呼ばれます。Function Import は、単純型かエンティティ型のコレクションを返しますが、値が返されない場合もあります。

[!メモ]

Function ImportEntityType を返すには、対応するストアド プロシージャによって返される列が、返される EntityType のプロパティと正確に一致する必要があります。

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

前提条件

このチュートリアルを完了するには、CourseManager アプリケーションを構築する必要があります。詳細情報と手順については、Entity Framework クイック スタートを参照してください。このアプリケーションを構築した後に、GetStudentGrades ストアド プロシージャに基づく Function Import を作成して EDM を変更します。

[!メモ]

このドキュメントのチュートリアルのトピックの多くは CourseManager アプリケーションを開始点としているため、元の CourseManager コードを編集するのではなく、このチュートリアル用に CourseManager アプリケーションのコピーを使用することをお勧めします。

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

Function Import の作成

この手順では、CourseManager EDM のストレージ モデルに含まれる GetStudentGrades ストアド プロシージャに基づく Function Import を作成します。

Function Import を作成するには

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

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

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

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

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

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

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

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

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

  7. [戻り値の型] ボックスの一覧から [CourseGrade] を選択します。

    [!メモ]

    GetStudentGrades ストアド プロシージャによって返される列 (EnrollementID および Grade) は CourseGrade エンティティ型のスカラ プロパティと正確に一致するので、戻り値の型を CourseGrade に設定できます。

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

    GetStudentGradesFunction Import が EDM に追加されます。

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

この手順では、選択した学生の成績を表示できるように、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 に、[テキスト]ViewGrades に設定します。

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

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

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

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

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

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

この手順では、前の手順で GetStudentGrades ストアド プロシージャから作成した Function Import を実行するコードを追加します。このコードは、返された EntityType コレクションを DataGridView コントロールにバインドします。オブジェクトをコントロールにバインドする方法の詳細については、「コントロールへのオブジェクトのバインド (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 _
        .Person.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.Person
        .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 フォームのデザイン ビューに戻り、studentListComboBox コントロールをダブルクリックします。

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

  6. studentList_SelectedIndexChanged イベント ハンドラに次のコードを追加します。このコードは、GetStudentGradesFunctionImport を実行し、ドロップダウン リストから新しい学生が選択されると 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)
    
    // 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);
    

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 _
            .Person.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)
    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.Person
                .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);
        }
    }
}

次の手順

ここでは、エンティティ型のコレクションを取得する Function Import を作成しました。Entity Framework でのストアド プロシージャのサポートの詳細については、「ストアド プロシージャのサポート (Entity Framework)」を参照してください。Entity Framework を使用するアプリケーションを構築する方法の詳細については、「プログラミング ガイド (Entity Framework)」を参照してください。

参照

その他のリソース

ADO.NET Entity Data Model デザイナのシナリオ
Entity Data Model ツールのタスク