Tuesday, 20 August 2013

Some Queries using Language integrated Query ( LINQ ).

Let Us perform some queries using Linq:

1. Retrieve all records from database
   sampleDataContext sdc = new sampleDataContext();
   //var data = from d in sdc.ToyShops select d ;(retrieve all records)
   var data = from d in sdc.ToyShops select new { id=d.toyId,name=d.toyname};// retrieve selected column
   dataGridView1.DataSource = data;

2. Update records from database
    sampleDataContext sdc = new sampleDataContext();
    ToyShop ts = sdc.ToyShops.Single(c => c.toyId == Convert.ToInt32(textBox1.Text));
    ts.toyname = textBox2.Text;
    sdc.SubmitChanges();
    MessageBox.Show("records Updated successfully !!");

3. Delete records from database
    sampleDataContext sdc = new sampleDataContext();
    ToyShop ts = sdc.ToyShops.Single(c => c.toyId == Convert.ToInt32(textBox1.Text));
    sdc.ToyShops.DeleteOnSubmit(ts);
    sdc.SubmitChanges();
    MessageBox.Show("records deleted  successfully !!");

4. Delete records from database
    sampleDataContext sdc = new sampleDataContext();
     ToyShop ts = new ToyShop();
     ts.toyId = Convert.ToInt32(textBox1.Text);
     ts.toyname = textBox2.Text;
     sdc.ToyShops.InsertOnSubmit(ts);
     sdc.SubmitChanges();
     MessageBox.Show("data inserted successfully ");

5. Skip() and Take()
     sampleDataContext sdc = new sampleDataContext();
     var data = (from d in sdc.ToyShops select d).Skip(1).Take(2);
     dataGridView1.DataSource = data;


6. Generate Computable fields using Linq
      sampleDataContext sdc = new sampleDataContext();
      //var data = from d in sdc.ToyShops select d ;(retrieve all records)
      var data = from d in sdc.ToyShops select new { id = d.toyId, name = d.toyname,price=d.price,quantity=d.nofQuantity,netPrice=d.price*d.nofQuantity };

      dataGridView1.DataSource = data;


Note :
Where Toyshop is the name of the Table in your database .

No comments:

Post a Comment