Export (0) Print
Expand All

How to: Execute a Query that Returns an Entity Type (Entity Framework)

This topic provides examples of how to execute an Entity SQL query that returns a collection of instances of an entity type. It then iterates through the collection of Products and displays the name and the ID for each Product. The same example is shown using each of the following Entity Framework query technologies:

The examples in this topic are based on the Adventure Works Sales Model. To run the code in this example, 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 LINQ to Entities example.

using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectQuery<Product> products = AWEntities.Product;
    IQueryable<Product> productsQuery = from product in products
                                        select product;

    Console.WriteLine("Product Names:");
    foreach (var prod in productsQuery)
    {
        Console.WriteLine(prod.Name);
    }
}

The following is the Entity SQL example.

using (AdventureWorksEntities advWorksContext =
    new AdventureWorksEntities())
{
    try
    {
        string queryString =
            @"SELECT VALUE Product FROM AdventureWorksEntities.Product AS Product";

        ObjectQuery<Product> productQuery =
            new ObjectQuery<Product>(queryString, advWorksContext, MergeOption.NoTracking);

        // Iterate through the collection of Product items.
        foreach (Product result in productQuery)
            Console.WriteLine("Product Name: {0}; Product ID: {1}",
                result.Name, result.ProductID);
    }
    catch (EntityException ex)
    {
        Console.WriteLine(ex.ToString());
    }
    catch (InvalidOperationException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

The following is the query builder method example.

using (AdventureWorksEntities advWorksContext =
    new AdventureWorksEntities())
{
    try
    {
        ObjectQuery<Product> productQuery = advWorksContext.Product;

        // Iterate through the collection of Product items.
        foreach (Product result in productQuery)
            Console.WriteLine("Product Name: {0}; Product ID: {1}",
                result.Name, result.ProductID);
    }
    catch (EntitySqlException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

See Also

Community Additions

Show:
© 2014 Microsoft