Share via


Learn LinqToSql Part 1

In this blog, I am going to give an example how to use linq to sql in your application

 

Let's create a c# console application first:

-File->New Project-> Visual C#->Console Application

Next step should be creating Linq to Sql Classes

-Right Click on your solution-> Add New Item-> Linq to Sql Classes->Click Add

This step is going to add required dlls + Dataclasses into your project

Now next step is to create your connection to datasource:

-Click View->Server Explorer->Right Click on Data connections and choose Add new Connection

-Specify DataSource name and credentials then database name ( I am choosing northwind database for my sample) and test connection

After these steps, in server explorer window, you will see your connection on the left side.

Next step is just drag/drop activity into Object Relational Designer Pane.

-Drag Employee table (from Server explorer window) and drop into Object Relational Designer Pane and save Dataclasses and save DataClass file.

Next step is to code in your application.

 

class Program
{
static void Main(string[] args)
{
DataClasses1DataContext dbcontext=new DataClasses1DataContext();

            var emp = from e in dbcontext.Employees
select e;
foreach ( Employee e in emp)
{
Console.WriteLine("First Name: {0} ,Last Name: {1} , City: {2}", e.FirstName,e.LastName,e.City);

            }
}
}

 

-Build and run your application and you will see results in console window.

That's it. This was our first sample. In next part, I will try to explain how to call stored procedures in Linq.

 

Please let me know if you have any questions.

 

Many Thanks

 

Kagan Arca

Comments