Monday, June 2, 2008

Linq to sql Tutorial


Language Integrated Query LINQ is a new query language being Introduced in ASP.NET 3.0 .
This language is based on ORM (object relational mapping) to make database queries much faster and safer .
Lets not get into details and get started with linq .........
We will follow a set of steps in implementing Linq to our project .

STEP:1 Open a visual studio project and connect to the required Sql database using the server explorer.

STEP:2 Add an new linq to sql file to your project.
This file has a .dbml extension ,simply drag and drop your database tables to this file.

STEP:3 Add namespace "using System.Data.Linq;" in your .aspx file .

STEP:4 Now start writing the queries to select,insert,update,delete data from the database table.
As you can see that my table contains four fields username,name,blogname and imageurl, the name of my database table is "linqprofile"and that of my .dbml file is "linqtry"
Select Query :
protected void Page_Load(object sender, EventArgs e)
{
linqtryDataContext db = new linqtryDataContext();//Create an instance of your linq datacontext
var us = db.linqprofiles.Where(u => u.username == "Learnlinq").Select(u=> u.name);
//var is an implicitly typed variable which has no datatype you can use string ,int etc if you know the datatype
Response.Write(us);
} //select name from the "linqprofiles" table where username is "Learnlinq"

Insert Query :
protected void Button1_Click(object sender, EventArgs e)
{
linqtryDataContext db = new linqtryDataContext();
linqprofile lp = new linqprofile { username = "newuser", name ="seconduser" ,blogname="insert",imageurl="C:\\blog.bmp" };

db.linqprofiles.InsertOnSubmit(lp);
db.SubmitChanges();

}

Delete Query :
protected void Button2_Click(object sender, EventArgs e)
{
linqtryDataContext db = new linqtryDataContext(); linqprofile lp = db.linqprofiles.First(p => p.username == "Learnlinq");
db.linqprofiles.DeleteOnSubmit(lp);
db.SubmitChanges();
}
//Delete the first record in "linqprofile" where username is "Learnlinq"

Update Query:
protected void Button3_Click(object sender, EventArgs e)
{

linqtryDataContext db = new linqtryDataContext(); linqprofile lp = db.linqprofiles.First(p => p.username == "Learnlinq");
lp.name = "anand";
db.SubmitChanges();

} //Update the first record in "linqprofile" table where username is "learnlinq"
//Update the name field to "anand"

I hope you now know how to update,insert,delete and select from the sql database .
Linq is even more intresting and we will talk more about linq in my later blogposts.

No comments: