Using the 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 incredibly simple. To see how it works, first open the AdventureWorksLT database in SQL Server Management Studio Express and examine the Customer, CustomerAddress, and Address tables. Make sure you understand their relationship, which is illustrated in the entity-relationship diagram in Figure 9-15.

AdventureWorksLT DB diagram

Figure 9-15. AdventureWorksLT DB diagram

Create a new Visual Studio Console Application called AdventureWorksDBML. Make sure that the Server Explorer is visible and that you have a connection to AdventureWorksLT, as shown in Figure 9-16. If the connection is not available, follow the instructions outlined earlier to create it.

Checking the AdventureWorksLT connection in the Server Explorer

Figure 9-16. Checking the AdventureWorksLT connection in the Server Explorer

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

When the New Item dialog opens, choose "LINQ to SQL Classes." You can use the default name for the class (probably DataClasses1), or replace it with a more meaningful one—we'll use AdventureWorksAddress. Now ...

Get Programming .NET 3.5 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.