|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. ArchiveDisclaimer|
How to: Create LINQ to SQL Classes in a Web Project
When you want to use Language-Integrated Query (LINQ) to access data in a database, you do not connect directly to the database. Instead, you create classes that represent the database and its tables, and use those classes to interact with data. You can generate the classes through the Object Relational Designer or by running the SqlMetal.exe utility. For more information, see Object Relational Designer (O/R Designer) and Code Generation Tool (SqlMetal.exe).
This topic shows how to use the O/R Designer in a Web application to create data classes that represent a SQL Server database.
In a Web site project, you must put the data classes in the project's App_Code folder or in a subfolder of App_Code. If you include the data classes in a subfolder of App_Code, the name of the subfolder will be used as the namespace for the classes. In that case, you must provide that namespace when you connect to the data classes. For a Web application project, you do not have to use the App_Code folder. You can put the data classes in the project folder. For information about the difference between Web site projects and Web application projects, see Web Application Projects versus Web Site Projects.
When you use the O/R Designer, the connection string for accessing the database is automatically added to the Web.config file.
To create a class from a database table
If the Web site does not already have an App_Code folder, in Solution Explorer, right-click the project, click Add ASP.NET Folder, and then click App_Code.
Right-click the App_Code folder and then click Add New Item.
Under Installed templates, select Linq to SQL Classes template, type a name for the .dbml file, and then click Add.
The Object Relational Designer window is displayed.
In Server Explorer, drag the database table into the Object Relational Designer window.
The table and its columns are represented as an entity in the designer window.
Save the .dbml file.
This creates .designer.cs or .designer.vb file that is located under the .dbml file. The file contains a class that represents the database and a class that represents the table. The parameterless constructor for the database class reads the connection string from the Web.config file.