I currently have a populated datatable from an excel workbook that I am trying to insert into my database.
Both the datatable as well as the table in my database have matching structures.
IE: Matching types, columns, and order of elements
I have a class that represents my entity within the database that would look something like this:
public class MyObject
{
public int ID {get; set;}
public string Name {get; set;}
public string GUID {get; set;}
}
From what I have gathered from here I should be able to do the following to convert the data table I have created to a list of objects based off of MyObject.
public List<MyObject> ConvertDataTable(Datatable tbl)
{
List<MyObject> results = new <MyObject>();
foreach(DataRow row in tbl.Rows)
{
MyObject convertedObject = ConvertRowToMyObject(row)
results.Add(convertedObject);
}
return results
}
The linked post also shows that it's necessary to convert single rows to the proper object data types, but it's that already inherited from MyObject?
public MyObject ConvertRowToMyObject(DataRow row)
{
MyObject result = new MyObject();
// Here the above post shows assigning properties of MyObject from the
// DataRow
result.ID = row.GetString(1);
result.GUID = row.GetInt32(0);
result.Name = row.GetString(1);
// I haven't been able to get 'GetInt' or 'GetString' to work properly,
// but doesn't each property already have the correct type from
// MyObject?
return result;
}
Prior to inserting data is there a way to enumerate all items within a column such as -
foreach(DataColumn col in tbl.Columns)
But something that can iterate over,manipulate, and return data based off of values contained in a singular column?