Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a datatable into a POCO object in Asp.Net MVC?

How do I convert a datatable into a POCO object in Asp.Net MVC?

like image 370
Josh Avatar asked Aug 30 '09 14:08

Josh


2 Answers

Pass each DataRow into the class constructor (or use getters/setters) and translate each column into the corresponding property. Be careful with nullable columns to extract them properly.

  public class POCO
  {
       public int ID { get; set; }
       public string Name { get; set; }
       public DateTime? Modified { get; set; }
       ...

       public POCO() { }

       public POCO( DataRow row )
       {
            this.ID = (int)row["id"];
            this.Name = (string)row["name"];
            if (!(row["modified"] is DBNull))
            {
                 this.Modified = (DateTime)row["modified"];
            }
            ...
       }
  }
like image 178
tvanfosson Avatar answered Nov 15 '22 07:11

tvanfosson


A data table typically holds many rows - do you want to convert each row into an object instance?

In that case, you could e.g. add a constructor to your POCO object that will accept a DataRow as parameter, and then extracts the bits and pieces from that DataRow:

public YourPOCO(DataRow row)
{
   this.Field1 = row["Field1"].ToString();
   ...
   this.FieldN = Convert.ToInt32(row["FieldN"]);
}

and so on, and then call that constructor on each of the rows in the DataTable.Rows collection:

List<YourPOCO> list = new List<YourPOCO>();

foreach(DataRow row in YourDataTable.Rows)
{
   list.Add(new YourPOCO(row));
}

And you could then create a ASP.NET MVC view or partial view based on this "YourPOCO" type and use the "List" template to create a list of "YourPOCO" instances in a list-like display.

Marc

like image 33
marc_s Avatar answered Nov 15 '22 09:11

marc_s