LINQ to SQL Fundamentals

To begin, open Visual Studio, and create a new application named "Simple Linq to SQL" as a console application. Once the IDE is open, click on View, and open the Server Explorer and make a connection to the AdventureWorksLT database, and test that connection.

With that in place, you are ready to create a program that uses LINQ to connect your SQL database. You'll need to include the System.Data.Linq namespace in the references for your project as shown in Figure 15-4 so that the last two using statements will compile.

Adding a reference to System.Data.Linq

Figure 15-4. Adding a reference to System.Data.Linq

This will also create the mapping between each class property and the corresponding database column:

public class Customer
 {[Column] public string FirstName      { get; set; }
    [Column] public string LastName       { get; set; }
    [Column] public string EmailAddress   { get; set; }

Complete analysis follows Example 15-1.

Example 15-1. Simple LINQ to SQL

using System; using System.Data.Linq; using System.Data.Linq.Mapping; using System.Linq; namespace Simple_Linq_to_SQL { // customer class [Table(Name="SalesLT.Customer")] public class Customer { [Column] public string FirstName { get; set; } [Column] public string LastName { get; set; } [Column] public string EmailAddress { get; set; } // Overrides the Object.ToString( ) to provide a // string representation of the object properties. public override string ToString( ...

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.