Friday, May 18, 2012

LINQ to SQL – DELETE


LINQ to SQL – DELETE

Before writing a LINQ to SQL query, we first need to create a DataContext using the LINQ to SQL Classes template, to know more on how to create the DataContext refer to the post LINQ to SQL Sample

Once the DataContext is created we can query the Object model using LINQ queries, let us consider the Employee table which has the following structure.


DELETE is a regular database operation, involved in any Transaction processing system.
Assume we have the following data in the Employee and Department Tables

Table: Employee
ID
NAME
DOB
DOJ
DepartmentID
Salery
1
Tom
11/11/1967
05/01/2009
1
5000
2
Harry
10/07/1973
05/01/2009
2
6000
3
Peter
01/01/1982
01/01/2002
3
6500
4
John
05/04/1981
05/01/2009
3
7500
5
Charles
12/12/1973
05/01/2009
NULL
6500
6
Robert
10/07/1973
05/01/2009
4
5500

Table: Department
ID
NAME
1
Finance
2
Human Resources
3
IT
4
Sales
5
Marketing

The SQL query to delete data from the Employees table will be as follows.

DELETE Employee WHERE ID = 6

Now let us see the equivalent DELETE query in LINQ.

EmployeeClassesDataContext dbContext = new EmployeeClassesDataContext();

// Select the Employee to be Deleted
Employee objEmp = (Employee)(from e in dbContext.Employees where e.ID.Equals(6) select e).First();
           
// Delete the Employee
dbContext.Employees.DeleteOnSubmit(objEmp);
           
//Submit the changes to the Database
dbContext.SubmitChanges();

After this code is executed you can find the details of the Employee is removed from the table as follows.
ID
NAME
DOB
DOJ
DepartmentID
Salery
1
Tom
11/11/1967
05/01/2009
1
5000
2
Harry
10/07/1973
05/01/2009
2
6000
3
Peter
01/01/1981
01/01/2001
3
6500
4
John
05/04/1981
05/01/2009
3
7500
5
Charles
12/12/1973
05/01/2009
NULL
6500


Related Post



Search Flipkart Products:
Flipkart.com

1 comment:

Anonymous said...

what if you want to delete from department table in C#???