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.
Click to Enlarge
- Using Server Explorer, connect to the database.
- After you connect to the database, drag a table into the test.dbml. file
Click to Enlarge
- 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.
- 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);