I have the following class:
[Table(Name = "test")]
public class Test
{
private string _Name;
[Column(Storage = "_Name")]
public string Name
{
get { return this._Name; }
set { this._Name = value; }
}
private int _Age;
[Column(Storage = "_Age")]
public int Age
{
get { return this._Age; }
set { this._Age = value; }
}
public static DataTable ConvertListToDataTable(List<Test> table) // Used for SqlBulkCopy
{
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
foreach (Test row in table)
{
DataRow dr = dt.NewRow();
dr["Name"] = row.Name;
dr["Age"] = row.Age;
dt.Rows.Add(dr);
}
return dt;
}
}
But I'd like to abstract that ConvertListToDataTable
method out into a parent base class. Is that possible using reflection? I wouldn't even know where to start.
Note the DataTable will have columns that exactly match (in name without the _
and type) all the properties of the class with a [Column] attribute
This is the reason I want the DataTable
:
public void testBulkInsert(string connection, string table, DataTable dt)
{
using (SqlConnection con = new SqlConnection(connection))
{
con.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(con))
{
bulkCopy.DestinationTableName = table;
bulkCopy.WriteToServer(dt);
}
}
}