Follow these steps to use the O/R Designer to generate a simple C# object model:

Open Visual Studio and create a console application named LinqToSql.

Right-click the project in the Solution Explorer pane and select Add New Item…from the context menu to open the Add New Item dialog. Select the Linq to SQL file template in the Data category. Change the Name to MyDataClasses.dbml. Click the Add button to close the Add New Item dialog. The empty design surface for the new dbml file appears, representing the DataContext that you will configure next. LINQ to SQL files have the extension .dbml.

In Server Explorer, right-click on the Data Connections node and select Add Connection from the context menu to open the Add Connection dialog. Complete the dialog to create a connection to the AdventureWorks database on your SQL Server. Click OK to close the dialog and create the connection.

Expand the new data connection in the Data Connections node. Drag the Product (Production) table from the table subnode onto the O/R Designer design surface to create the entity class Product—the new class contains properties corresponding to columns in the Product table. Next, drag the ProductInventory (Production) table onto the design surface to create the entity class ProductInventory. Notice that an association (relationship) is automatically created between the two entities based on the database metadata. The design surface is shown in Figure A-21.

Build the project.

Open the Data Sources pane by selecting Data Show Data Sources from the main menu. Click the Add New Data Source link to open the Data Source Configuration Wizard dialog. Select Object as the data source type. Click Next.

Expand the LinqToSql node. Navigate to and select the Product class. Click Next. Click Finish to confirm that you want to add the Product entity class. The Product and its related ProductInventory classes are added to the Data Sources pane, as shown in Figure A-22.

Next, create the LINQ to SQL query to return data from the Product table using the Product entity class. The completed C# code for Program.cs is shown in the following example:

using System;
using System.Linq;

namespace LinqToSql

class Program
static void Main(string[] args)
MyDataClassesDataContext dc =
new MyDataClassesDataContext();

var products = from row in dc.Products
where row.ProductID < 100
select row;

foreach (Product p in products)
Console.WriteLine(p.ProductID + ": " + p.Name);

Console.WriteLine("\nPress any key to continue.");

No comments: