Simple Insert,Update,View and Delete with LINQ-To-SQL

No.of Views2226
Bookmarked0 times
Downloads 
Votes0
By  jalpesh   On  17 May 2010 08:05:54
Tag : LINQ , T-SQL
Today one of my friend asked me about simple insert,update and delete example with LINQ-To-SQL but at that time i was not having any simple example which will show the power of LINQ-To-SQL Example
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

Today one of my friend asked me about simple insert,update and delete example with LINQ-To-SQL but at that time i was not having any simple example which will show the power of LINQ-To-SQL Example

So i have decided to create one simple example with LINQ-To-SQL and also decide to blog about it. Let's create a simple example which is very simple and also show basic step to use LINQ-To-SQL. First i have created a simple table called which have 4 fields like ProductId,Name,Description and Price. Like following.

 

Image Loading

Here is the description for each fields

  1. ProductId- A id which uniquely identify each product.
  2. Name- Name of Product
  3. Description- A short description about product
  4. Price- Price of Product.

Now, Lets create a Linq-To-SQL and rename it as MyDataContent.dbml as following. For that Go to your project ->Right Click->Add New Item->Go to Data Template-> LINQ to SQL Classes like following.

 

Image Loading

Then open Database Explorer and drag and drop Product table on the newly generated LINQ-to-SQL Class like following.

 

Image Loading

Now our LINQ-SQL-Class is Ready. Now we will insert some data to our table and then first we will write code to get all product information from the database. I have created a function called GetProduct which will print all the product information on page with the help of Response.Write . Following is code for that.

public void GetProducts()
{
using (MyDataContentDataContext context = new MyDataContentDataContext())
{
var Products = from product in context.Products
             orderby product.Name
             select product;
foreach(Product p in Products)
{
Response.Write(string.Format("<B>Id</B>:{0}", p.ProductId.ToString()));
Response.Write(string.Format("<B>Name</B>:{0}", p.Name));
Response.Write(string.Format("<B>Description</B>:{0}", p.Description));
Response.Write(string.Format("<B>Price</B>:{0}", p.Price.ToString()));
Response.Write("===========================================");
}
}
}

Now Let's Create a function to Add Product. Following is code for function to add product.

public void AddProduct(Product product)
{
using (MyDataContentDataContext context = new MyDataContentDataContext())
{
context.Products.InsertOnSubmit(product);
context.SubmitChanges();
}
}

In the above function i am passing a new object of product and passing that object to above function following is a code for that which create a new product via calling above function.
 

//Add New Product
Product product = new Product();
product.Name = "Product3";
product.Description="This is product 3 Description";
product.Price=10;
AddProduct(product);

Now we have added the code to add product now lets create a function to update the current product information. Following is a code for that.

public void UpdateProduct(int productId, string name, string description, double price)
{
using (MyDataContentDataContext context = new MyDataContentDataContext())
{
 Product currentProduct = context.Products.FirstOrDefault(p => p.ProductId == productId);
 currentProduct.Name = name;
 currentProduct.Description = description;
 currentProduct.Price = price;
 context.SubmitChanges();
}
}

With the help of above function you can update current product like following.

////Update Product
UpdateProduct(2,"New Product2","New Description for product",20); 

Now we added the code for update product so now let's create a sample code to delete a specific product. Following is a code for that.

public void DeleteProduct(int productId)
{
using (MyDataContentDataContext context = new MyDataContentDataContext())
{
Product currentProduct = context.Products.FirstOrDefault(p => p.ProductId == productId);
context.Products.DeleteOnSubmit(currentProduct);
context.SubmitChanges();
}
}

You can delete the product via passing product id as following.

//Delete product
DeleteProduct(3);

So that's it. you can create insert,update,delete operation with the help of LINQ-To-SQL within some minutes without writing so much code for .net and queries for databases.

Happy Programming...

 
Sign Up to vote for this article
 
About Author
 
jalpesh
Occupation-Software Engineer
Company-DotNetJaps
Member Type-Expert
Location-India
Joined date-08 May 2010
Home Page-http://www.dotnetjalps.com
Blog Page-http://www.dotnetjalps.com
I am jalpesh vadgamaa an Microsoft MVP for Visual C# and BrainBench Certified ASP.NET Developer having experience of five year in Microsoft .NET Technology.I am working as Project Leader in Mid Size company.My work area comprises of Enterprise Level projects using ASP.NET and other Microsoft .NET Technologies.Please feel free to contact me for any queries via posting comments on my blog I will try to reply as early as possible.
 
 
Other popularSectionarticles
    In this article, I am going to show how you can filter your data by RowNumbers that you assigned to your records.
    Published Date : 03/Feb/2011
    SelectMany is Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence.In this post I am going to show how you can use SelectMany Extension method to achieve the join between related tables easily without writing long queries.
    Published Date : 18/Jan/2011
    Now a days most of the developers are moving towards new LINQ to SQL they find difficult to write down SQL query in C# to query data using LINQ. LINQ is a query language which get integrated in C# to query data form ObjectCollects, SQL, XML etc.
    Published Date : 08/Jan/2011
    I have already written several article about Linq its a great ORM that we can use in various way. The purpose of this post to demonstrate How we can bind custom entity to stored procedure result with use of Linq-To-SQL.
    Published Date : 05/Aug/2010
    After two decades, the industry has reached a stable point in the evolution of object-oriented (OO) programming technologies
    Published Date : 12/May/2010
Comments
By:RRaveenDate Of Posted:9/22/2010 8:28:20 AM
Thank you for support
Hi Jalpesh and Charles Thank you for great support. i will try to get more articles in LINQ in codegain.com. thank you
By:Jalpesh VadgamaDate Of Posted:9/22/2010 12:34:10 AM
Thank for appreciation
There are lots of stuff there on internet nowdays and you can do lots of stuff with linq there. http://jalpesh.blogspot.com/search/label/LINQ here is link where i have posted the linq related articles. Also scott gu has published series of articles for linq. http://weblogs.asp.net/scottgu/archive/2006/05/14/Using-LINQ-with-ASP.NET-_2800_Part-1_2900_.aspx
By:Charles TeagueDate Of Posted:9/21/2010 1:15:32 PM
Thank You - Do you know of a good overview of Linq
Thank you for the easy to follow examples of how to do select, insert, update, delete for Linq 2010 to SQL. Do you know of where I can find a simple overview of Linq? I found the one on Wikipedia hard to follow.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top