如何:执行多态查询
本主题说明如何使用 OFTYPE 运算符执行多态实体 SQL 查询。
运行本示例中的代码
将学校模型添加到项目,并将项目配置为使用实体框架。 有关详细信息,请参阅如何:使用实体数据模型向导。
在应用程序的代码页中,添加以下
using
指令(在 Visual Basic 中为Imports
):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