Thursday, August 20, 2009

Simple LINQ Insert, Update , Delete Tutorial in C#

  • Open a new Visual Studio windows application project (c#)

  • Right click the project and goto AddNew item. and it will popup the following dialog.
  • select the Linq to SQL Classes and give a neme add click add. then double click the added class in your solution explorer. Then it will load following type of screen.

  • In the Data connection (Assumme you already created a SQL Server Database and also a table nemed "Table1"), Drag and drop the table to the window. Then it will ask for connection string saving dialog. For the moment keep it NO.
  • Now we will see how to use LINQ to do Insert , Update , Delete.
  • Coding is describing below. (sample is the name given by me to the LinqtoSQL class).

private void cmdAdd_Click(object sender, EventArgs e)
{
    sampleDataContext Dt = new sampleDataContext();
    Table1 T = new Table1();
    T.Address = "Address 1";
    T.Name = "a";
 
    Dt.Table1s.InsertOnSubmit(T);
    Dt.SubmitChanges();
}
 
private void cmdUpdate_Click(object sender, EventArgs e)
{
    sampleDataContext Dt = new sampleDataContext();
 
    Table1 t = Dt.Table1s.Single(p => p.Name == "a");
    t.Address = "address2";
    Dt.SubmitChanges();
}
 
private void cmdDelete_Click(object sender, EventArgs e)
{
    sampleDataContext Dt = new sampleDataContext();
 
    Table1 t = Dt.Table1s.Single(p => p.Name == "a");
    Dt.Table1s.DeleteOnSubmit(t);
    Dt.SubmitChanges();
}

Post a Comment