How to: Connect to a Database

How to: Connect to a Database

.NET Framework (current version)

The DataContext is the main conduit by which you connect to a database, retrieve objects from it, and submit changes back to it. You use the DataContext just as you would use an ADO.NET SqlConnection. In fact, the DataContext is initialized with a connection or connection string that you supply. For more information, see DataContext Methods (O/R Designer).

The purpose of the DataContext is to translate your requests for objects into SQL queries to be made against the database, and then to assemble objects out of the results. The DataContext enables Language-Integrated Query (LINQ) by implementing the same operator pattern as the Standard Query Operators, such as Where and Select.

System_CAPS_security Security Note

Maintaining a secure connection is of the highest importance. For more information, see Security in LINQ to SQL.


In the following example, the DataContext is used to connect to the Northwind sample database and to retrieve rows of customers whose city is London.

// DataContext takes a connection string. 
DataContext db = new DataContext(@"c:\Northwnd.mdf");

// Get a typed table to run queries.
Table<Customer> Customers = db.GetTable<Customer>();

// Query for customers from London.
var query =
    from cust in Customers
    where cust.City == "London"
    select cust;

foreach (var cust in query)
    Console.WriteLine("id = {0}, City = {1}", cust.CustomerID, cust.City);

Each database table is represented as a Table collection available by way of the GetTable<TEntity> method, by using the entity class to identify it.


Best practice is to declare a strongly typed DataContext instead of relying on the basic DataContext class and the GetTable<TEntity> method. A strongly typed DataContext declares all Table collections as members of the context, as in the following example.

public partial class Northwind : DataContext
    public Table<Customer> Customers;
    public Table<Order> Orders;
    public Northwind(string connection) : base(connection) { }

You can then express the query for customers from London more simply as:

Northwnd db = new Northwnd(@"c:\Northwnd.mdf");
var query =
    from cust in db.Customers
    where cust.City == "London"
    select cust;
foreach (var cust in query)
    Console.WriteLine("id = {0}, City = {1}", cust.CustomerID,
© 2016 Microsoft