Single post

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;
}

//

umar
August 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

Rami
September 30th, 2009 at 1:39 pm

Thank you, very helpful
:)

Rami
September 30th, 2009 at 2:15 pm

it explode when var query equals to singleResult :|

junior
October 22nd, 2011 at 3:42 am

very good code!
But what kind of object to pass as argument to that method ?

Ali
December 18th, 2011 at 6:54 pm

Thanks a lot

LEAVE A COMMENT

theme by teslathemes