Using Visual Studio LINQ to SQL Designer

Rather than working out the data relationships in the underlying database and mapping them in the DataContext manually, you can use the designer built into Visual Studio. This is a very powerful mechanism that makes working with LINQ painfully simple. To see how this works, first open the AdventureWorksLT database in SQL Server Management Studio Express and examine the Customer, CustomerAddress, and Address tables so that you feel comfortable you understand their relationship, as illustrated by the Entity-Relationship diagram shown in Figure 15-5.

AdventureWorksLT database diagram

Figure 15-5. AdventureWorksLT database diagram

Create a new Visual Studio console application called AdventureWorksDBML. Make sure the Server Explorer is visible and you have a connection to AdventureWorksLT, as shown in Figure 15-6. If the connection is not available, follow the instructions mentioned earlier to create it.

Server Explorer window

Figure 15-6. Server Explorer window

To create your LINQ to SQL classes, right-click on the project, and choose Add → New Item, as shown in Figure 15-7.

Selecting Add→New Item

Figure 15-7. Selecting Add→New Item

When the New Item dialog opens, choose LINQ to SQL Classes. You can use the default name (probably DataClasses1), ...

Get Programming C# 3.0, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.