 |
LINQ - Tutorial LINQ to SQL - Generating DataContext |
 |
 |
|
|
Prerequisites:
Goals:
- Generate classes for LINQ to SQL for the Northwind database.
Steps:
- Create a new Console Application project.
- Add to the project a new item - 'LINQ to SQL Classes'. Name it 'Nortwind.dbml':

- According to the description displayed in the designer of the NorthwindDataClasses.dbml
file, open the Server Explorer window and add a new connection:
- Choose 'Microsoft SQL Server' as a 'Data Source'.
- Write the name of the local SQL Server instance (if the
default installation was done, there is an instance named '<machine_name>\SQLEXPRESS',
e.g. 'KMOSSAKOWSKI\SQLEXPRESS').
- Use the default 'Windows Authentication' or change it, if
the configuration of the SQL Server instance was changed.
- Write the name of the database: 'Northwind' (see
prerequisites of this tutorial).
- Press the 'Test Connection' button to check if the
connection can be established:

- Expand the new created connection in the Server Explorer window and
than expand also the 'Tables' node. Select all tables and drag them to the
'Object Relational Designer' window opened for the NorthwindDataClasses.dbml:

- Examine all files generated by Visual Studio:
- NorthwindDataClasses.dbml - note the definition of the
database structure in the XML format
- NorthwindDataClasses.cs
- NorthwindDataClasses.dbml.layout
- NorthwindDataClasses.designer.cs - note C# classes generated
for each table dragged from the Server Explorer window
- Settings.settings
- Settings.Designer.cs
- app.config
- To check if everything is OK, write to the console the number of
customers stored in the Northwind database:
static
void
Main(string[]
args)
{
NorthwindDataContext
dataContext = new
NorthwindDataContext();
Console.WriteLine(dataContext.Customers.Count());
}
Alternatively, the SqlMetal.exe command line tool can be used for generating
the DataContext classes and all classes representing tables.
[Source code]