Querying and updating a database table

Now that we have the entity classes created, we will use them to interact with the database. We will first work with the products table to query and update records as well as to insert and delete records.

Querying records

First we will query the database to get some products.

To query a database by using LINQ to Entities, we first need to construct a DbContext object, as follows:

NorthwindEntities NWEntities = new NorthwindEntities();

We can then use the LINQ query syntax to retrieve records from the database:

IEnumerable<Product> beverages = from p in NWEntities.Products
                     where p.Category.CategoryName == "Beverages"
                     orderby p.ProductName
                     select p;

The preceding code will retrieve all of the products in the Beverages ...

Get WCF 4.5 Multi-Layer Services Development with Entity Framework now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.