Language preference:

Phase 1 / Introducing the DataContext class

Each Data Access Layer technology creates a class to describe the overall structure of your database. It defines each Entity class that maps to a table in the database. It knows about the relationships between tables and can return query results based on those relationships. In BLD, we call this a DataContext class.

Note: There are many names used for this class. Entity Framework calls it ObjectContext. Some call it Domain. Others call it Model. LINQ to SQL actually does call it DataContext. BLD will use “DataContext” except when showing an example specific to the DAL technology.

LINQ to SQL and ADO.NET Entity Framework automatically generate DataContext classes when you run their code generators. Being in the Data Access Layer, you never modify it.

Example using Entity Framework

Using NorthWind database with its Categories and Products tables.

public partial class NorthWindEntities : global::System.Data.Objects.ObjectClass
{
  public ObjectSet<Category> Categories
  {
    get
    {
        if ((_Categories == null))
            _Categories = base.CreateObjectSet<Category>("Categories");
        return _Categories;
    }
  }
  private ObjectSet<Category> _Categories;

  public ObjectSet<Product> Products
  {
    get
    {
        if ((_Products == null))
            _Products = base.CreateObjectSet<Product>("Products");
        return _Products;
    }
  }
  private ObjectSet<Product> _Products;
}

The next topic describes how to create a DataContext using code generators that come with Visual Studio.