Retrieving Data

Replace the contents of Program.cs with the code shown in Example 15-2 to use the generated LINQ to SQL code to retrieve data from the three tables you've mapped using the designer.

Example 15-2. Using LINQ to SQL designer-generated classes

using System; using System.Linq; using System.Text; namespace AdventureWorksDBML { // Main program public class Tester { static void Main( ) { AdventureWorksAddressDataContext dc = new AdventureWorksAddressDataContext( ); // Uncomment the statement below to show the // SQL statement generated by LINQ to SQL. // dc.Log = Console.Out; // Find one customer record. Customer donna = dc.Customers.Single(c => c.FirstName == "Donna");"); Console.WriteLine(donna); // Find a list of customer records. var customerDs = from customer in dc.Customers where customer.FirstName.StartsWith("D") orderby customer.FirstName, customer.LastName select customer; foreach (Customer customer in customerDs) { Console.WriteLine(customer); } } } // Add a method to the generated Customer class to // show formatted customer properties. public partial class Customer { public override string ToString( ) { StringBuilder sb = new StringBuilder( ); sb.AppendFormat("{0} {1} {2}", FirstName, LastName, EmailAddress); foreach (CustomerAddress ca in CustomerAddresses) { sb.AppendFormat("\n\t{0}, {1}", ca.Address.AddressLine1, ca.Address.City); } sb.AppendLine( ); return sb.ToString( ); } } } Output: Donna Carreras donna0@adventure-works.com 12345 Sterling Avenue, Irving ...

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.