Tuesday, August 26, 2008

LINQ

LINQ - LANGUAGE INTEGRATED QUERY

ENVIRONMENT:




  1. Create DataClasses1.dbml.

  2. Create a database Test with table test which has Id (integer, PK) and Name (varchar(10)).

  3. Create a stored procedure GetDatas

  4. Using server explorer connect to database Test and add the table "test" and Stored proceure "getDatas" in the DataClasses1.dbml

* Once the dbml file is created system automatically creates a class "DataClasses1DataContext"

EXAMPLES

  1. Retrieve data from Table test

    using (DataClasses1DataContext dc = new DataClasses1DataContext())
    IEnumerable t = from b in dc.tests select b; //where b.name.StartsWith("Ra")
    foreach (test t1 in t)
    {
    Console.WriteLine(t1.name);
    }
    }

  2. retrieve data from Stored Procedure
    using (DataClasses1DataContext dc = new
    {
    var t = from b in dc.getDatas() select b;
    foreach (var t1 in t)
    {
    Console.WriteLine(t1.name);
    }
    }

  3. Insert in to Table test

    using (DataClasses1DataContext dc = new DataClasses1DataContext())
    {
    test d = new test();
    d.name = 'n';
    dc.duplicates.InsertOnSubmit(d);
    dc.SubmitChanges();
    }

  4. Updation
    using (DataClasses1DataContext dc = new DataClasses1DataContext())
    {
    IEnumerable t = from b in dc.tests select b; //where b.name.StartsWith("Ra")
    //Update Table
    test t2 = t.Single((a) => a.ID == 1);
    t2.name = "updated";
    dc.SubmitChanges();
    }


* If the datable doesn't contain primary key , you will not able to do insertion , updation and deletion . To
achieve this add attribute to any one of the column for that table in DataClasses1DataContext class as follows
[Column(Storage = "_id", DbType = "Int", IsPrimaryKey = true)]
public System.Nullable id
{
get
{
return this._id;
}
set
{
if ((this._id != value))
{
this._id = value;
}
}
}




No comments: