Get LINQ to SQL results into a DataTable

There are two ways to get LINQ to SQL results into a DataTable, as explained here.

I use Sample II:

public DataTable ToDataTable(System.Data.Linq.DataContext ctx, object query)
{
     if (query == null)
     {
          throw new ArgumentNullException("query");
     }

     IDbCommand cmd = ctx.GetCommand(query as IQueryable);
     SqlDataAdapter adapter = new SqlDataAdapter();
     adapter.SelectCommand = (SqlCommand)cmd;
     DataTable dt = new DataTable("sd");

     try
     {
          cmd.Connection.Open();
          adapter.FillSchema(dt, SchemaType.Source); 
          adapter.Fill(dt);
     }
     finally
     {
          cmd.Connection.Close();
     }
     return dt;
}

//

  • Share/Bookmark

3 Comments

umarAugust 28th, 2009 at 10:04 am

Very Good Help, I was searching this article to extend my knowledge from Linq To Sql and using DataTable in Linq To Sql.
many many thankx

RamiSeptember 30th, 2009 at 1:39 pm

Thank you, very helpful
:)

RamiSeptember 30th, 2009 at 2:15 pm

it explode when var query equals to singleResult :|

Leave a comment

Your comment