Uğur UMUTLUOĞLU
Web Technologies, Microsoft and .NET Technologies

Insert, Update & Delete in LINQ to SQL

Saturday, 9 August 2008 23:07 by ugur

Insert, Update & Delete in LINQ to SQL As you know, we can make queries among collection based objects in .NET environment with the language integrated queries named LINQ. The main purpose of these queries is to simplify the complicated processes by writing simple Select queries just as in T-SQL; instead of using foreach loops and if-else control structures. The main issue point of LINQ is to provide making simple and practical queries among enormous and complicated data objects (entity objects) in an application and to reduce one of the heavy weights of the software developers in extended projects.

One of the most frequently asked questions related to LINQ to SQL is how to carry out Insert, Update and Delete processes. I think it is not needed to be said that; it can not be made queries with the key words Insert, Update and Delete in LINQ statementsJ Thus, if the purpose is to work with the data objects in LINQ to SQL, somehow we need to perform these kind of actions. LINQ to SQL Classes (.dbml) files provide us to transform the data objects from database straightly to our application as classes. For example, if we form Product table included in Northwind database as data class in our application, the Products property included in DataContext object will return the records in Products table as the collection. Some methods of this property will help us to perform query statements like Insert, Update and Delete.

With InsertOnSubmit statement we can perform Insert act and with DeleteOnSubmit statement we can perform Delete act. Okay, but where is Update act? We will perform Update act by changing the values of the record or records return as LINQ query result. In order to transfer the results of these three acts to the database, it will be adequate to execute the SubmitChanges method of DataContext object. If you examine the code lines given below, you can see how to insert, delete and update data in LINQ to SQL. The Northwind object included in code snippet is our DataContext object.

Product addPr = new Product() { ProductName="Acer Aspire 5100", UnitPrice=1290, UnitsInStock=15, CategoryID=9 };

northWind.Products.InsertOnSubmit(addPr); // A new product added to insert list

 

Product updatePr = northWind.Products.First(u => u.ProductID == 69);

guncellenecekUrun.ProductName = "HP Pavilion 3355"; // ProductName property has changed for selected product

 

Product deletePr = northWind.Products.First(u => u.ProductID == 79);

northWind.Products.DeleteOnSubmit(deletePr); // Selected product added to delete list

 

northWind.SubmitChanges(); // Changes(insert/update/delete) has sent to database

Tags:   ,
Categories:   C#
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

Comments

 
Add to Technorati Favorites