Friday, August 15, 2008

[Tutorial] ADO.NET Entity Framework
Part 2 - Accessing data and using LINQ (1/2)

The last part of the series described how to set up a project for using the Framework. This part shows how to easily query information from the configured data sources. You need to have a console project with an ADO.NET data model that links to the AdventureWorks DB as prerequisite for the following examples.

The first example shows how to easily display information from within the DB with very little code.

  • Initialize an object of the auto-generated AdventureWorksEntities class and display some product data.

  • Run the application and you will get the following output.

This is the easiest but also the most inflexible way of accessing data from the configured entities. It will not really be sufficient if you need more control over the data. Using LINQ will give you everything necessary to really have maximum flexibility.

  • The following example displays the same results as the last example but this time by using LINQ.

  • A good practice is to externalize the creation of the LINQ query for better extensibility, readability and understanding. I also restricted the result to have just 20 elements since we don't need to query all products.

  • Run the application and you will get the following output.


No comments: