- Introduction
- LINQ to SQL in a Nutshell
- Mapping Entity Classes to Tables
- Defining a Custom DataContext
- Querying the CreditCard Table with LINQ
- Summary
Defining a Custom DataContext
The DataContext class is analogous to the SqlConnection. The DataContext essentially contains the connection string for the database. You also can add helper properties that retrieve mapped tables. Listing 2 contains a DataContext that represents the AdventureWorks database and a helper property that returns the mapped CreditCard entity.
Listing 2 The custom DataContext with the connection string and the helper property.
// custom datacontext class public class AdventureWorks : DataContext { private static readonly string connectionString = @"Data Source=.\SQLExpress;Initial Catalog=AdventureWorks;" + "Integrated Security=True"; public AdventureWorks() : base(connectionString) { } public Table<CreditCard> CreditCards { get { return this.GetTable<CreditCard>(); } } }
In Listing 2, AdventureWorks inherits from DataContext. Simply creating an instance of the AdventureWorks class gives you an implicit connection to the database. To return a collection of CreditCard objects, declare the property using the generic Table<T> type, where T is CreditCard.