如何:执行多态查询 (EntityClient)
本主题说明如何使用 OFTYPE 运算符执行多态 Entity SQL 查询。
运行本示例中的代码
生成 CourseManager 应用程序。有关更多信息和说明,请参见实体框架快速入门。
执行演练:映射继承 - 每个层次结构一个表的“实现每个层次结构一个表继承”一节中的指令以修改其 EDM。
示例
OFTYPE 表达式指定一个类型表达式,此表达式旨在针对集合的每个元素执行类型测试。OFTYPE 表达式生成指定类型的新集合,其中仅包含等效于该类型或其子类型的那些元素。例如,如果 Manager 是 Employee 的子类型,则以下表达式将从员工集合生成仅包含经理的集合:
OfType(employees, Manager)
下面的示例使用 OFTYPE 运算符从 People 的集合中获取和显示仅包含 Students 的集合。
Using connection As EntityConnection = New EntityConnection("name= SchoolEntities ")
connection.Open()
' Create a query that specifies to
' get a collection of Students
' with enrollment dates from
' a collection of People.
Dim esqlQuery As String = "SELECT Student.LastName, " & _
" Student.EnrollmentDate FROM " & _
" OFTYPE(SchoolEntities.Person, " & _
" SchoolModel.Student) AS Student "
' Create an EntityCommand and pass the connection object
' and Enity SQL query to its constructor.
Using command As EntityCommand = New EntityCommand(esqlQuery, connection)
' Execute the command.
Using reader As DbDataReader = command.ExecuteReader(CommandBehavior.SequentialAccess)
' Start reading.
Do While reader.Read
' Display student's last name and enrollment date.
Console.Write(reader.Item("LastName"))
Console.WriteLine(reader.Item("EnrollmentDate"))
Loop
End Using
End Using
End Using
using (EntityConnection conn = new EntityConnection("name=SchoolEntities"))
{
conn.Open();
// Create a query that specifies to
// get a collection of only Students
// with enrollment dates from
// a collection of People.
string esqlQuery = @"SELECT Student.LastName,
Student.EnrollmentDate FROM
OFTYPE(SchoolEntities.Person,
SchoolModel.Student) AS Student";
using (EntityCommand cmd = new EntityCommand(esqlQuery, conn))
{
// Execute the command.
using (DbDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
// Start reading.
while (rdr.Read())
{
// Display student's last name and enrollment date.
Console.Write(rdr["LastName"] + " ");
Console.WriteLine(rdr["EnrollmentDate"]);
}
}
}
}
另请参见
任务
如何:使用每个层次结构一个表继承创建和执行对象查询(实体框架)
概念
其他资源
使用 EntityClient(实体框架任务)
How to: Execute an Entity SQL Query Using EntityCommand