Cómo ordenar datos (Entity Framework)

En este tema se describe cómo ordenar los resultados de una consulta. Este ejemplo devuelve una colección de objetos Contact ordenados alfabéticamente por la primera letra del apellido de Contact.LastName. Se muestra el mismo ejemplo con las siguientes tecnologías de consulta de Entity Framework:

  • LINQ to Entities

  • Entity SQL con ObjectQuery<T>

  • Métodos del generador de consultas de ObjectQuery<T>

Los ejemplos de este tema se basan en el modelo Adventure Works Sales. Para ejecutar el código de este ejemplo, debe haber agregado ya el modelo AdventureWorks Sales al proyecto y haber configurado el proyecto para usar Entity Framework. Para ello, complete los procedimientos de Cómo configurar manualmente un proyecto de Entity Framework y Cómo definir manualmente un modelo Entity Data Model (Entity Framework). También puede utilizar el Asistente para Entity Data Model con el fin de definir el modelo AdventureWorks Sales. Para obtener más información, vea Cómo usar el Asistente para Entity Data Model (Entity Framework).

Ejemplo

A continuación se muestra el ejemplo de LINQ to Entities.

Using context As AdventureWorksEntities = _
  New AdventureWorksEntities()
    Try
        ' Define a query that returns a list 
        ' of Contact objects sorted by last name.
        Dim sortedNames = _
        From n In context.Contact _
        Order By n.LastName _
        Select n

        Console.WriteLine("The sorted list of last names:")
        For Each name As Contact In sortedNames
            Console.WriteLine(name.LastName)
        Next
    Catch ex As EntitySqlException
        Console.WriteLine(ex.ToString())
    End Try
End Using
using (AdventureWorksEntities context = 
    new AdventureWorksEntities())
{
    try
    {
        // Define a query that returns a list 
        // of Contact objects sorted by last name.
        var sortedNames =
            from n in context.Contact
            orderby n.LastName
            select n;

        Console.WriteLine("The sorted list of last names:");
        foreach (Contact name in sortedNames)
        {
            Console.WriteLine(name.LastName);
        }
    }
    catch (EntitySqlException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

A continuación se muestra el ejemplo de Entity SQL.

' Define the Entity SQL query string that returns 
' Contact objects sorted by last name.
Dim queryString As String = "SELECT VALUE n FROM Contact AS n " _
        + "Order By n.LastName"

Using context As AdventureWorksEntities = _
    New AdventureWorksEntities()
    Try
        ' Define an ObjectQuery that returns a collection 
        ' of Contact objects sorted by last name.
        Dim query As ObjectQuery(Of Contact) = _
            New ObjectQuery(Of Contact)(queryString, context)

        Console.WriteLine("The sorted list of last names:")
        For Each name As Contact _
        In query.Execute(MergeOption.AppendOnly)
            Console.WriteLine(name.LastName)
        Next
    Catch ex As EntitySqlException
        Console.WriteLine(ex.ToString())
    End Try
End Using
// Define the Entity SQL query string that returns 
// Contact objects sorted by last name.
string queryString = @"SELECT VALUE n FROM Contact AS n 
        Order By n.LastName";

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    try
    {
        // Define an ObjectQuery that returns a collection 
        // of Contact objects sorted by last name.
        ObjectQuery<Contact> query = 
            new ObjectQuery<Contact>(queryString, context);

        Console.WriteLine("The sorted list of last names:");
        foreach (Contact name in query.Execute(MergeOption.AppendOnly))
        {
            Console.WriteLine(name.LastName);
        }
    }
    catch (EntitySqlException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

A continuación se muestra el ejemplo del método del generador de consultas.

Using context As AdventureWorksEntities = _
    New AdventureWorksEntities()
    Try
        ' Define an ObjectQuery that returns a collection 
        ' of Contact objects sorted by last name.
        Dim query As ObjectQuery(Of Contact) = _
        context.Contact.OrderBy("it.LastName")

        Console.WriteLine("The sorted list of last names:")
        For Each name As Contact _
        In query.Execute(MergeOption.AppendOnly)
            Console.WriteLine(name.LastName)
        Next
    Catch ex As EntitySqlException
        Console.WriteLine(ex.ToString())
    End Try
End Using
using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    try
    {
        // Define an ObjectQuery that returns a collection 
        // of Contact objects sorted by last name.
        ObjectQuery<Contact> query = 
            context.Contact.OrderBy("it.LastName");

        Console.WriteLine("The sorted list of last names:");
        foreach (Contact name in query.Execute(MergeOption.AppendOnly))
        {
            Console.WriteLine(name.LastName);
        }
    }
    catch (EntitySqlException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

Vea también

Otros recursos

Consultar un Entity Data Model (tareas de Entity Framework)