Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

How to: Order Two Unionized Queries (Entity Framework)

This topic shows how to combine the results of two queries into a single result set, and then order the result set. The same example is shown using each of the following Entity Framework query technologies:

The examples in this topic are based on the AdventureWorks Sales Model (EDM). To run the code in these examples, you must have already added the AdventureWorks Sales Model to your project and configured your project to use the Entity Framework. To do this, complete the procedures in How to: Manually Configure an Entity Framework Project and How to: Manually Define an Entity Data Model (Entity Framework). You can also use the Entity Data Model Wizard to define the AdventureWorks Sales Model. For more information, see How to: Use the Entity Data Model Wizard (Entity Framework).

Example

The following is the Entity SQL example. To unionize and order Entity SQL queries, you must use nesting. In Entity SQL, nested queries must be enclosed in parentheses.

using (AdventureWorksEntities advWorksContext =
    new AdventureWorksEntities())
{
    String esqlQuery = @"SELECT P2.Name, P2.ListPrice
        FROM ((SELECT P1.Name, P1.ProductID as Pid, P1.ListPrice 
            FROM AdventureWorksEntities.Product as P1
            where P1.Name like 'A%')
        union all
            (SELECT P1.Name, P1.ProductID as Pid, P1.ListPrice 
            FROM AdventureWorksEntities.Product as P1
            WHERE P1.Name like 'B%')
        ) as P2
        ORDER BY P2.Name";
    try
    {
        foreach (DbDataRecord rec in
            new ObjectQuery<DbDataRecord>(esqlQuery, advWorksContext))
        {
            Console.WriteLine("Name: {0}; ListPrice: {1}", rec[0], rec[1]);
        }
    }
    catch (EntityException ex)
    {
        Console.WriteLine(ex.ToString());
    }
    catch (InvalidOperationException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

This is the query builder method example.

using (AdventureWorksEntities advWorksContext =
    new AdventureWorksEntities())
{
    ObjectQuery<DbDataRecord> query = 
        advWorksContext.Product.Select("it.Name, it.ProductID As Pid, it.ListPrice")
        .Where("it.Name LIKE 'A%'").Union(advWorksContext.Product
        .Select("it.Name, it.ProductID As Pid, it.ListPrice")
        .Where("it.Name LIKE 'B%'")).Select("it.Name, it.ListPrice").OrderBy("it.Name");

        try
        {
            foreach (DbDataRecord rec in query)
            {
                Console.WriteLine("Name: {0}; ListPrice: {1}", rec[0], rec[1]);
            }
        }
        catch (EntitySqlException ex)
        {
            Console.WriteLine(ex.ToString());
        }
}

See Also

Community Additions

Show:
© 2015 Microsoft