tags:

views:

758

answers:

1

Hi,

Is there any quick way to create a table in a dataset and fill it with the schema from an IQueryable (Data is not coming from EF or Linq2Sql)? I need this for binding a grid to my data.

Thanks, Roy

+1  A: 

You can use the Translate function of the System.Data.Linq.DataContext class to "automatically" map a Table into a Class.

There is an example:

using System.Data.Linq;
using System.Data.SqlClient;



    string cnnStr = "YourConnectionString";
    DataContext dc = new DataContext(cnnStr);
    SqlConnection sqlCnn = (SqlConnection) dc.Connection;
    sqlCnn.Open();
    SqlCommand sqlCmd = new SqlCommand("select ID, Name, [Date] From test", sqlCnn);
    SqlDataReader sqlDr = sqlCmd.ExecuteReader();
    var result = dc.Translate<clsRow>(sqlDr);
    foreach(clsRow row in result)
    {
       Console.Write(row.ID);
       Console.Write(row.Name);
       Console.Write(row.Date);
    }

In this case, you need a table called Test with 3 columns: ID, Name and Test and also a class called clsRow in .Net with the same properties name of the table columns.

public class clsRow
{
    public int ID { get; set; }
    public string Name { get; set; }
    public DateTime Date { get; set; }
}