作法:執行多型查詢
此主題示範如何使用 OFTYPE 運算子來執行多型 Entity SQL 查詢。
執行此範例中的程式碼
將 School 模型新增至您的專案,並設定專案使用 Entity Framework。 如需詳細資訊,請參閱操作說明:使用實體資料模型精靈。
在應用程式的代碼頁中,新增下列
using
指示詞 (Imports
在 Visual Basic 中):using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.EntityClient; using System.Data.Metadata.Edm;
Imports System.Collections.Generic Imports System.Collections Imports System.Data.Common Imports System.Data Imports System.IO Imports System.Data.SqlClient Imports System.Data.EntityClient Imports System.Data.Metadata.Edm
遵循逐步解說:對應繼承 - 每個階層的資料表中的步驟,修改概念模型以擁有每個階層的資料表繼承。
範例
下列範例會使用 OFTYPE 運算子,從 OnsiteCourses
的集合中取得並顯示只有 Courses
的集合。
using (EntityConnection conn = new EntityConnection("name=SchoolEntities"))
{
conn.Open();
// Create a query that specifies to
// get a collection of only OnsiteCourses.
string esqlQuery = @"SELECT VAlUE onsiteCourse FROM
OFTYPE(SchoolEntities.Courses, SchoolModel.OnsiteCourse)
AS onsiteCourse";
using (EntityCommand cmd = new EntityCommand(esqlQuery, conn))
{
// Execute the command.
using (DbDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
// Start reading.
while (rdr.Read())
{
// Display OnsiteCourse's location.
Console.WriteLine("CourseID: {0} ", rdr["CourseID"]);
Console.WriteLine("Location: {0} ", rdr["Location"]);
}
}
}
}
Using conn As New EntityConnection("name=SchoolEntities")
conn.Open()
' Create a query that specifies to
' get a collection of only OnsiteCourses.
Dim esqlQuery As String = "SELECT VAlUE onsiteCourse FROM " & _
"OFTYPE(SchoolEntities.Courses, SchoolModel.OnsiteCourse) AS onsiteCourse"
Using cmd As New EntityCommand(esqlQuery, conn)
' Execute the command.
Using rdr As DbDataReader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)
' Start reading.
While rdr.Read()
' Display OnsiteCourse's location.
Console.WriteLine("CourseID: {0} ", rdr("CourseID"))
Console.WriteLine("Location: {0} ", rdr("Location"))
End While
End Using
End Using
End Using