0

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?

4
  • why not do the manipulation in the ConvertRowToMyObject it self ? you can get the values of a column in data row by using row["column name"] Commented Jul 6, 2016 at 14:29
  • @Dheeraj So, in the third snippet what is the purpose of assigning types If I had already done so in the MyObject class? I assumed it was as easy as that...what would row["Name"] return then? (what type)? Commented Jul 6, 2016 at 14:32
  • It would return a type object you can use row.Field<type>("fieldName"); instead this should work from .NET 4.0 Commented Jul 6, 2016 at 14:44
  • @Dheeraj I attempted both ways: DataRow dr = dt.NewRow(); dr["NAME"].ToString(); // As well as dr.Field<myObject>("NAME"); Both of these throw the error of Column 'NAME' does not belong to table, but when I view my datatable it does in fact exist in the table, Commented Jul 6, 2016 at 14:52

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.