Articles → .NET → Using LINQ to SQL for single table

Using LINQ to SQL for single table







•  Create a web based application.

•  Right click on project

•  Click "Add New Item".

•  Select "LINQ to SQL classes" from "Add New Item Template" and name them say test.dbml.

Picture showing selecting the LINQ to SQL data item while adding a new item in the project

Click to Enlarge

•  Using Server Explorer, connect to the database.

•  After you connect to the database, drag a table into the

Picture showing dragging and dropping the person entity on the dbml file

Click to Enlarge

•  When you drag the table, a class

•  Apart from that another class




Fetching Data




testDataContext obj = new testDataContext();
var per = from c in obj.Persons  select c;
GridView1.DataSource = per;
GridView1.DataBind();



Inserting Data


testDataContext obj = new testDataContext();
Person p1 = new Person();
p1.PersonID = 5;
p1.PersonName = "karan";
p1.stateID = 2;
p1.Address = "ee";
obj.Persons.InsertOnSubmit(p1);
obj.SubmitChanges();



Updating Data


testDataContext obj = new testDataContext();
Person p1 = obj.Persons.Single(p => p.PersonID == 1);
p1.PersonName = "karan1";
p1.Address = "Gurgaon";
obj.SubmitChanges();



Deleting Data


testDataContext obj = new testDataContext();
Person p1 = obj.Persons.Single(p => p.PersonID == 4);
obj.Persons.DeleteOnSubmit(p1);
obj.SubmitChanges();



Executing Stored Procedure




Create Proc test_proc @PersonID int AS BEGIN 
delete from 
  Person 
where 
  PersonID = @PersonID END




testDataContext obj = new testDataContext();
obj.test_proc(1);



Posted By  -  Karan Gupta
 
Posted On  -  Thursday, November 25, 2010

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250