Search This Blog

Wednesday, February 9, 2011

How can Use LINQ in C#

Language Integrated Query (LINQ) adds the ability to query objects using .NET languages. The LINQ to SQL object/relational mapping framework provides the following basic features:
LINQ has a power of querying on any source of data, data source could be the collections of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable interface. Microsoft basically divides LINQ into three areas and that are give below.

•LINQ to Object {Queries performed against the in-memory data}
•LINQ to ADO.Net
◦LINQ to SQL (formerly DLinq) {Queries performed against the relation database only Microsoft SQL Server Supported}
◦LINQ to DataSet {Supports queries by using ADO.NET data sets and data tables}
◦LINQ to Entities {Microsoft ORM solution}
•LINQ to XML (formerly XLinq) { Queries performed against the XML source}
Tools to create classes (usually called entities) mapped to database tables
Compatibility with LINQ’s standard query operations
The DataContext class, with features such as entity record monitoring, automatic SQL statement generation, record concurrency detection

Code for LINQ**************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using pmsContract.entities;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Data.Linq;
using System.Data.Linq.Mapping;

namespace pms.Webproject
{
//we have create class usertest and table nam: pms_user

[Table(Name = "pms_user")]//define table name
public class usertest //this is classs
{
[Column]
public string userfname { get; set; } //get or set table fields
[Column]
public string userlname { get; set; }
[Column]
public string useremailID { get; set; }

}

public partial class test : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{
string conn = ConfigurationManager.ConnectionStrings["stringConnection"].ToString();
DataContext db = new DataContext(conn);//Interface between linq or SQL
Table<usertest> pmsusettest = db.GetTable<usertest>();//create object of table
var query = from d in pmsusettest orderby d.userfname select d; //select linq query for data selection.
GridView1.DataSource = query;//provide datasource to gridview
GridView1.DataBind();
}

}
}

4 comments :

Anonymous said...

Hi,
I have done this Linq and was going through your article but your explanation of code is wrong. This is not the right way man.
If you share something explain it in right manner and with right code.

Anonymous said...

Dear User,
I am very happy from your response if u think this is worng that means you konw that right way please kindly request to you post with explanation in right way.

thanks

Anonymous said...

Hi,

This code is working fine at my end.
thanks for a great job.....

Anonymous said...

it is working but i can't understand
the below line does
Table pmsusettest = db.GetTable();