Partilhar via


LINQ to SQL : What is DataContext.Translate Method

DataContext’s Translate method converts existing IDataReader to an IEnumerable<T>. This is very useful when you may need to run raw SQL Query though System.Data.Linq. I am getting few similarities with DataContext’s ExecuteQuery.

 

How Translate works

+++++++++++++

Assuming I am using Northwind database.

 

 

using (NWDataContext db = new NWDataContext())

{

    DbConnection conn = db.Connection;

    conn.Open();

    DbCommand comm = conn.CreateCommand();

    comm.CommandText = "SELECT * FROM Customers";

    DbDataReader reader = comm.ExecuteReader();

    var q = db.Translate<Customer>(reader);

    ObjectDumper.Write(q);

}

 

Now since my dbml has Customer class defined and I am running SELECT * query this can map with existing Customer class. But if I want to retrieve only the selected columns from the result set then one of the drawbacks is that I cannot project the output using Anonymous Type, rather I need to define a class in my app to project it to IEnumerable<T>. One of the reasons is that the Anonymous Type does not create any default public constructor. It would have been nice to have this anonymous type projection with the Translate.

 

So if you want to map it to your type then your approach would be little different.

 

using (NWDataContext db = new NWDataContext())

{

    DbConnection conn = db.Connection;

    conn.Open();

    DbCommand comm = conn.CreateCommand();

    comm.CommandText = "SELECT CustomerId, CompanyName FROM Customers";

    DbDataReader reader = comm.ExecuteReader();

    var q = db.Translate<CustomerSelect>(reader);

    ObjectDumper.Write(q);

}

 

Extra things you need is that,

 

class CustomerSelect

{

    public int CustID { get; set; }

    public string CompanyName { get; set; }

}

 

Whereas in ExecuteQuery method you do things little differently,

 

using (NWDataContext db = new NWDataContext())

{

    var q = db.ExecuteQuery<Customer>("SELECT * FROM Customers", "");

    ObjectDumper.Write(q);

}

 

 

Namoskar!!!

Comments

  • Anonymous
    December 18, 2007
    DataContext’s Translate method converts existing IDataReader to an IEnumerable&lt;T&gt;. This is very

  • Anonymous
    December 19, 2007
    Link Listing - December 18, 2007

  • Anonymous
    December 19, 2007
    Code Camps Swag Scrooges [Via: Steve ] Philly Code Camp Registration Open [Via: Chip Lemmon ] Link...

  • Anonymous
    April 26, 2008
    This code is somewhat misleading. It only works because you are retrieving the list inside of the using statement. If you want to pass q out of a method that performs this operation ... you must not use the Using statement.