Procedura: utilizzare percorsi di query per influenzare i risultati (Entity Framework)
In questo argomento viene fornito un esempio che illustra come specificare un percorso della query per definire gli oggetti correlati restituiti quando viene eseguita una query su un oggetto specifico in Entity Data Model (EDM). La query di questo esempio restituisce un singolo oggetto Contact e tutti gli oggetti SalesOrderHeader e SalesOrderDetail correlati. Lo stesso esempio viene illustrato utilizzando ognuna delle tecnologie di query Entity Framework seguenti:
LINQ to Entities
Entity SQL con ObjectQuery<T>
Metodi del generatore di query di ObjectQuery<T>
L'esempio incluso in questo argomento è basato sul modello Sales di AdventureWorks. Per eseguire il codice incluso in questo esempio, è necessario avere già aggiunto il modello Sales di AdventureWorks al progetto e avere configurato il progetto per l'utilizzo di Entity Framework. A tale scopo, completare le procedure descritte in Procedura: configurare manualmente un progetto di Entity Framework e Procedura: definire manualmente un modello EDM (Entity Framework). È inoltre possibile utilizzare la procedura guidata Entity Data Model per definire il modello Sales di AdventureWorks. Per ulteriori informazioni, vedere Procedura: utilizzare la procedura guidata Entity Data Model (Entity Framework).
Esempio
Di seguito è riportato un esempio di utilizzo di LINQ to Entities.
Using context As New AdventureWorksEntities
' Define a LINQ query with a path that returns
' orders and items for a contact.
Dim contacts = (From contact In context.Contact _
.Include("SalesOrderHeader.SalesOrderDetail") _
Select contact).FirstOrDefault()
Try
' Execute the query and display information for each item
' in the orders that belong to the contact.
For Each order As SalesOrderHeader In contacts.SalesOrderHeader
Console.WriteLine(String.Format("PO Number: {0}", _
order.PurchaseOrderNumber))
Console.WriteLine(String.Format("Order Date: {0}", _
order.OrderDate.ToString()))
Console.WriteLine("Order items:")
For Each item As SalesOrderDetail In order.SalesOrderDetail
Console.WriteLine(String.Format("Product:{0}" _
+ "Quantity: {1}", item.ProductID.ToString(), _
item.OrderQty.ToString()))
Next
Next
Catch ex As EntitySqlException
Console.WriteLine(ex.ToString())
Catch ex As EntityCommandExecutionException
Console.WriteLine(ex.ToString())
End Try
End Using
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
// Define a LINQ query with a path that returns
// orders and items for a contact.
var contacts = (from contact in context.Contact
.Include("SalesOrderHeader.SalesOrderDetail")
select contact).FirstOrDefault();
try
{
// Execute the query and display information for each item
// in the orders that belong to the contact.
foreach (SalesOrderHeader order in contacts
.SalesOrderHeader)
{
Console.WriteLine(String.Format("PO Number: {0}",
order.PurchaseOrderNumber));
Console.WriteLine(String.Format("Order Date: {0}",
order.OrderDate.ToString()));
Console.WriteLine("Order items:");
foreach (SalesOrderDetail item in order.SalesOrderDetail)
{
Console.WriteLine(String.Format("Product: {0} "
+ "Quantity: {1}", item.ProductID.ToString(),
item.OrderQty.ToString()));
}
}
}
catch (EntitySqlException ex)
{
Console.WriteLine(ex.ToString());
}
catch (EntityCommandExecutionException ex)
{
Console.WriteLine(ex.ToString());
}
}
Di seguito è riportato un esempio di utilizzo di Entity SQL.
Using context As New AdventureWorksEntities
' Define an object query with a path that returns
' orders and items for a specific contact.
Dim queryString As String = _
"SELECT VALUE TOP(1) Contact FROM " + _
"AdventureWorksEntities.Contact AS Contact"
' Define the object query with the query string.
Dim contactQuery As New ObjectQuery(Of Contact)(queryString, _
context, MergeOption.NoTracking)
Dim contact As Contact = _
contactQuery.Include("SalesOrderHeader.SalesOrderDetail") _
.FirstOrDefault()
Try
' Execute the query and display information for each item
' in the orders that belong to the first contact.
For Each order As SalesOrderHeader In contact.SalesOrderHeader
Console.WriteLine(String.Format("PO Number: {0}", _
order.PurchaseOrderNumber))
Console.WriteLine(String.Format("Order Date: {0}", _
order.OrderDate.ToString()))
Console.WriteLine("Order items:")
For Each item As SalesOrderDetail In order.SalesOrderDetail
Console.WriteLine(String.Format("Product:{0}" _
+ "Quantity: {1}", item.ProductID.ToString(), _
item.OrderQty.ToString()))
Next
Next
Catch ex As EntitySqlException
Console.WriteLine(ex.ToString())
Catch ex As EntityCommandExecutionException
Console.WriteLine(ex.ToString())
End Try
End Using
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
// Define an object query with a path that returns
// orders and items for a specific contact.
string queryString =
@"SELECT VALUE TOP(1) Contact FROM " +
"AdventureWorksEntities.Contact AS Contact";
// Define the object query with the query string.
ObjectQuery<Contact> contactQuery = new ObjectQuery<Contact>(queryString,
context, MergeOption.NoTracking);
Contact contact =
contactQuery.Include("SalesOrderHeader.SalesOrderDetail")
.FirstOrDefault();
try
{
// Execute the query and display information for each item
// in the orders that belong to the first contact.
foreach (SalesOrderHeader order in contact
.SalesOrderHeader)
{
Console.WriteLine(String.Format("PO Number: {0}",
order.PurchaseOrderNumber));
Console.WriteLine(String.Format("Order Date: {0}",
order.OrderDate.ToString()));
Console.WriteLine("Order items:");
foreach (SalesOrderDetail item in order.SalesOrderDetail)
{
Console.WriteLine(String.Format("Product: {0} "
+ "Quantity: {1}", item.ProductID.ToString(),
item.OrderQty.ToString()));
}
}
}
catch (EntitySqlException ex)
{
Console.WriteLine(ex.ToString());
}
catch (EntityCommandExecutionException ex)
{
Console.WriteLine(ex.ToString());
}
}
Di seguito è riportato l'esempio del metodo del generatore di query.
Using context As New AdventureWorksEntities
' Create an object query with a path that returns orders and items for a contact.
Dim contact As Contact = _
context.Contact.Include("SalesOrderHeader.SalesOrderDetail") _
.FirstOrDefault()
Try
' Execute the query and display information for each item
' in the orders that belong to the returned contact.
Dim order As SalesOrderHeader
For Each order In contact.SalesOrderHeader
Console.WriteLine(String.Format("PO Number: {0}", _
order.PurchaseOrderNumber))
Console.WriteLine(String.Format("Order Date: {0}", _
order.OrderDate.ToString()))
Console.WriteLine("Order items:")
Dim item As SalesOrderDetail
For Each item In order.SalesOrderDetail
Console.WriteLine(String.Format("Product:{0}" _
+ "Quantity: {1}", item.ProductID.ToString(), _
item.OrderQty.ToString()))
Next
Next
Catch ex As EntitySqlException
Console.WriteLine(ex.ToString())
Catch ex As EntityCommandExecutionException
Console.WriteLine(ex.ToString())
End Try
End Using
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
// Define an object query with a path that returns
// orders and items for a specific contact.
Contact contact =
context.Contact.Include("SalesOrderHeader.SalesOrderDetail")
.FirstOrDefault();
try
{
// Execute the query and display information for each item
// in the orders that belong to the first contact.
foreach (SalesOrderHeader order in contact
.SalesOrderHeader)
{
Console.WriteLine(String.Format("PO Number: {0}",
order.PurchaseOrderNumber));
Console.WriteLine(String.Format("Order Date: {0}",
order.OrderDate.ToString()));
Console.WriteLine("Order items:");
foreach (SalesOrderDetail item in order.SalesOrderDetail)
{
Console.WriteLine(String.Format("Product: {0} "
+ "Quantity: {1}", item.ProductID.ToString(),
item.OrderQty.ToString()));
}
}
}
catch (EntitySqlException ex)
{
Console.WriteLine(ex.ToString());
}
catch (EntityCommandExecutionException ex)
{
Console.WriteLine(ex.ToString());
}
}
Vedere anche
Attività
Procedura: eseguire una query che restituisce un tipo di entità (Entity Framework)
Procedura: spostarsi nelle relazioni utilizzando le proprietà di navigazione (Entity Framework)
Concetti
Determinazione della struttura dei risultati di query (Entity Framework)
Metodi del generatore di query (Entity Framework)
Panoramica su Entity SQL