locked
Linq query to DataTable RRS feed

  • Question

  • Is there option to convert from Linq.IQueryable to DataTable with some sort of CopyToDataTable() function. I am trying this.

        var row = from p in dc.ProductModels
                      select p;
        DataTable dt = row.CopyToDataTable();
    
    


    asim
    Monday, August 23, 2010 6:31 PM

Answers

  •  //Get linq-query as datatable-schema
        public DataTable ToDataTable(System.Data.Linq.DataContext ctx, object query)
        {
          if (query == null)
          {
            throw new ArgumentNullException("query");
          }
    
          IDbCommand cmd = ctx.GetCommand((IQueryable)query);
          System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter();
          adapter.SelectCommand = (System.Data.SqlClient.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;
        }
    

    Did I got you Right?

     

    Rgrds...


    Regards, GoodLuck.
    Tuesday, August 24, 2010 9:35 AM

All replies

  •  //Get linq-query as datatable-schema
        public DataTable ToDataTable(System.Data.Linq.DataContext ctx, object query)
        {
          if (query == null)
          {
            throw new ArgumentNullException("query");
          }
    
          IDbCommand cmd = ctx.GetCommand((IQueryable)query);
          System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter();
          adapter.SelectCommand = (System.Data.SqlClient.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;
        }
    

    Did I got you Right?

     

    Rgrds...


    Regards, GoodLuck.
    Tuesday, August 24, 2010 9:35 AM
  • i think he means something like this (doesnt work by the way), where the table or resulttype isnt defined/contained in the datacontext and he wants to return something a little more complex than a basic type like <String>

    somecontrol.DataSource = dc.ExecuteQuery<DataTable>(@"select col1, col2 from table");

    at least this is what i was trying to do when i googled this page.

    Tuesday, January 25, 2011 7:18 PM