Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

How to: Connect to a Database (LINQ to SQL)

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.

Security noteSecurity 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.

No code example is currently available or this language may not be supported.

Each database table is represented as a Table collection available by way of the GetTable 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 method. A strongly typed DataContext declares all Table collections as members of the context, as in the following example.

No code example is currently available or this language may not be supported.

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

No code example is currently available or this language may not be supported.

Community Additions

ADD
Show:
© 2015 Microsoft