Книга: C# 2008 Programmer

Modeling Databases Using LINQ to SQL

Modeling Databases Using LINQ to SQL

The example web application will display records from two tables in the pubs sample database. Because you are going to use LINQ to access the database, you do not connect to the database directly. Instead, you generate classes that represent the database and its tables and then use those classes to interact with the data. To begin, add a new item to the project and select the LINQ to SQL Classes template (see Figure 17-3).

Figure 17-3

Use the default name of DataClasses.dbml. When prompted to save the item in the App_Code folder, click Yes. The DataClasses.dbml file is created in the App_Code folder of your project (see Figure 17-4).

Figure 17-4

The Object Relational Designer (O/R Designer) then launches so that you can visually edit the databases and tables you want to use. Open the Server Explorer window, and connect to the pubs sample database. Drag and drop the publisher and title tables onto the design surface of DataClasses.dbml (see Figure 17-5).

Figure 17-5

Save the DataClasses.dbml file by pressing Ctrl+S. When you save the file, Visual Studio 2008 persists out .NET classes that represent the entities and database relationships that you have just added. For each LINQ to SQL designer file you add to your solution, a custom DataContext class is generated. It is the main object that you use to manipulate the table. In this example, the DataContext class is named DataClassesDataContext.

Be sure to save DataClasses.dbml before proceeding.

Оглавление книги

Генерация: 1.114. Запросов К БД/Cache: 3 / 1
Вверх Вниз