Ескертпе
Бұл бетке кіру үшін қатынас шегін айқындау қажет. Жүйеге кіруді немесе каталогтарды өзгертуді байқап көруге болады.
Бұл бетке кіру үшін қатынас шегін айқындау қажет. Каталогтарды өзгертуді байқап көруге болады.
Рассмотрим, как выполнить команду для концептуальной модели с использованием объекта EntityCommand и как получить результат с вложенной коллекцией при использовании EntityDataReader.
Выполнение кода в этом примере
Добавьте модель продаж AdventureWorks в проект и настройте проект для использования 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
Пример
Вложенная коллекция — это коллекция, находящаяся внутри другой коллекции. В следующем коде происходит получение коллекции Contacts и вложенных коллекций SalesOrderHeaders, которые связаны с каждым объектом Contact.
using (EntityConnection conn =
new EntityConnection("name=AdventureWorksEntities"))
{
conn.Open();
// Create an EntityCommand.
using (EntityCommand cmd = conn.CreateCommand())
{
// Create a nested query.
string esqlQuery =
@"Select c.ContactID, c.SalesOrderHeaders
From AdventureWorksEntities.Contacts as c";
cmd.CommandText = esqlQuery;
// Execute the command.
using (EntityDataReader rdr =
cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
// The result returned by this query contains
// ContactID and a nested collection of SalesOrderHeader items.
// associated with this Contact.
while (rdr.Read())
{
// the first column contains Contact ID.
Console.WriteLine($"Contact ID: {rdr["ContactID"]}");
// The second column contains a collection of SalesOrderHeader
// items associated with the Contact.
DbDataReader nestedReader = rdr.GetDataReader(1);
while (nestedReader.Read())
{
Console.WriteLine($" SalesOrderID: {nestedReader["SalesOrderID"]} ");
Console.WriteLine($" OrderDate: {nestedReader["OrderDate"]} ");
}
}
}
}
conn.Close();
}
Using conn As New EntityConnection("name=AdventureWorksEntities")
conn.Open()
' Create an EntityCommand.
Using cmd As EntityCommand = conn.CreateCommand()
' Create a nested query.
Dim esqlQuery As String = "Select c.ContactID, c.SalesOrderHeaders" & _
" From AdventureWorksEntities.Contacts as c"
cmd.CommandText = esqlQuery
' Execute the command.
Using rdr As EntityDataReader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)
' The result returned by this query contains
' ContactID and a nested collection of SalesOrderHeader items.
' associated with this Contact.
While rdr.Read()
' the first column contains Contact ID.
Console.WriteLine("Contact ID: {0}", rdr("ContactID"))
' The second column contains a collection of SalesOrderHeader
' items associated with the Contact.
Dim nestedReader As DbDataReader = rdr.GetDataReader(1)
While nestedReader.Read()
Console.WriteLine(" SalesOrderID: {0} ", nestedReader("SalesOrderID"))
Console.WriteLine(" OrderDate: {0} ", nestedReader("OrderDate"))
End While
End While
End Using
End Using
conn.Close()
End Using