LINQ to SQL Basics – Part 2 (Creating LINQ to SQL Classes)

I will show you how to create LINQ to SQL data classes within your existing project. I will be using Northwind within my example.

Right click on your project, Add, New Item…

 

Under Visual C# Items, select Data. Under Templates select LINQ to SQL Classes and enter your name for your data context and click Add.

 

Click Server Explorer inside the Northwind.dbml file

In the server explorer tab click the connect to database icon.

 

Setup your database connection and click ok.

 

Now you will be able to add all your tables and stored procedures to your data context. Highlight the tables that you want to add and drag them on your data context. Do the same with the stored procedures.

 

Now we will be able to write LINQ queries…

Add the following using statement on the page where you going to use your LINQ query:

using System.Linq;

I used the following code to test the LINQ functionality in a console app:

using System;

using System.Linq;

 

namespace LINQtoSQLPart2

{


class
Program

{


static
void Main(string[] args)

{


NorthwindDataContext db = new
NorthwindDataContext();

 


var q = from c in db.Customers


select c;

 


foreach (var row in q)

{


Console.WriteLine(“Customer: {0}”, row.CompanyName);

}


Console.ReadLine();

}

}

}

That’s all to it…

Advertisement
Published in: on April 6, 2009 at 7:22 am  Leave a Comment  
Tags: ,

The URI to TrackBack this entry is: http://mvkatredleaf.wordpress.com/2009/04/06/linqtosqlbasicspart2/trackback/

RSS feed for comments on this post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.