Databases Reference
In-Depth Information
ObjectContext and Simple Queries
Another class automatically generated by the Entity Designer is the ObjectContext called
NorthwindEntities , shown here in pseudo-code form:
public partial class NorthwindEntities : ObjectContext
{
public ObjectSet<Product> Products { get; }
}
An ObjectContext encapsulates a database connection, allows you to query the database
using LINQ (Language Integrated Query), and manipulate data rows using entity classes
instead of the general-purpose DataRow objects used with classic ADO.NET. Here is how we
can retrieve a list of products for which the number of units in stock dropped below the
reorder level:
using (NorthwindEntities context = new NorthwindEntities())
{
var query = from p in context.Products
where p.UnitsInStock < p.ReorderLevel
select p;
foreach (Product p in query)
Console.WriteLine(p.ProductName);
}
The Products property of the NorthwindEntities class encapsulates the Products database
table. It returns an ObjectSet of Product instances, which can be used in LINQ queries
such as the one in the example just displayed.
Associations
The entity model can also define associations between entities. In the database, relation-
ships are represented as foreign keys, such as the one from the SupplierID column of the
Products table referencing the SupplierID column of the Suppliers table. To take advantage
of this capability of the Entity Framework, you need to add the Suppliers table to the
entity model. The easiest way to do this with an existing database is by using the Update
Wizard. Simply right-click the surface of the Entity Designer and choose Update Model
from Database…. This brings up an Update Wizard dialog, similar to the one shown in
Figure 2.6.
 
Search WWH ::




Custom Search