Sunday, January 30, 2011

Insert, Update, Delete Operation in LINQ to SQL????

Here I give you simple example to understand basic database functionality using LINQ

Table structure :

Id(Primary key, Auto Increment)    Int
Name                                             nvarchar(50)
Age                                                nvarchar(50)


Insert operation:

protected void btn_Insert_Click(object sender, EventArgs e)
    {
        DataClassesDataContext db_Context = new DataClassesDataContext();

        Customer cus = new Customer()
        {
            Name = TextBox1.Text,
            Age = TextBox2.Text
        };

        db_Context.Customers.InsertOnSubmit(cus);
        db_Context.SubmitChanges();
    }


Update operation:

protected void btn_Update_Click(object sender, EventArgs e)
    {
        DataClassesDataContext db_context = new DataClassesDataContext();

        Customer cus = db_context.Customers.Single(c => c.ID == 1);
        cus.Name = TextBox1.Text;
        cus.Age = TextBox2.Text;

        db_context.SubmitChanges();
    }


Delete operation:


 protected void btn_Delete_Click(object sender, EventArgs e)
    {
        DataClassesDataContext db_context = new DataClassesDataContext();       
        var cusdata = (from cus in db_context.Customers where cus.Age == "30" select cus).First();
        db_context.Customers.DeleteOnSubmit(cusdata);
        db_context.SubmitChanges();
    }

No comments:

Post a Comment