Export (0) Print
Expand All

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.

After you create the classes, you can connect to the classes by using the LinqDataSource control, the ObjectDataSource control, or a LINQ query.

To create a class from a database table

  1. 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.

  2. Right-click the App_Code folder and then click Add New Item.

  3. 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.

  4. 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.

  5. 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.

Community Additions

ADD
Show:
© 2014 Microsoft