Articles → .NET → Using LINQ To SQL For Single Table

Using LINQ To SQL For Single Table







  1. Create a web-based application.
  2. Right click on project
  3. Click "Add New Item".
  4. Select "LINQ to SQL classes" from "Add New Item Template" and name them say test.dbml.
  5. Picture showing selecting the LINQ to SQL data item while adding a new item in the project
    Click to Enlarge

  6. Using Server Explorer, connect to the database.
  7. After you connect to the database, drag a table into the test.dbml. file
  8. Picture showing dragging and dropping the person entity on the dbml file
    Click to Enlarge

  9. When you drag the table, a class Person is added for the table. In this class property is defined for each column of the database table.
  10. Apart from that another class testDataContext is created inherits from System.Data.Linq.DataContext , we are using this class further while we manipulate data from the database.



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