Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create DataTable with DB table structure

Tags:

c#

sql-server

What is the best way to create a DataTable with the same structure as a table in my SqlServer database? At present, I am using SqlDataAdapter.Fill() with a query that brings back the columns but no rows. That's works fine, but it seems klutzy.

Is there a better way?

like image 225
SeaDrive Avatar asked Aug 31 '25 02:08

SeaDrive


1 Answers

Well, if you use Linq2Sql, you can reflect over the entity class, and create the datatable based on the properties name and datatype.

            Type type = typeof(Product); //or whatever the type is
            DataTable table = new DataTable();
            foreach(var prop in type.GetProperties())
            {
                table.Columns.Add(prop.Name, prop.PropertyType);
            }
like image 171
BFree Avatar answered Sep 02 '25 16:09

BFree