views:

529

answers:

3

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

+6  A: 

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"];
            }
            ...
       }
  }
tvanfosson
@tvanfosson: why do you always have to have the same ideas as I do, and type 5 seconds faster than me :-)
marc_s
I can control time and read minds. :-o
tvanfosson
What is modified here? I understand that we should check if any value in the row is null before assigning to the properties in the class. But,what are you referring to as modified?
Josh
Is it only a name given to datetime variable? but then why is it called modified?...something related specifically to datatable?
Josh
nevermind....I guess you just mean't the time when it was modified...Thanks
Josh
Yeah -- those are just examples of column names.
tvanfosson
+3  A: 

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

marc_s
Thanks for mentioning the List<YourPOCO>.That made it more clearer.
Josh
+1  A: 

I saw your other question about using a datatable in the data access layer. If you return POCO at some point its a good idea to let your DAL return POCO already.

You would use an SqlDataReader to fill the POCO. This is more light weight. Sometimes its easier to use DataSet and DataTable for Lists of entries, but if you tranform the rows into stronly typed POCOS anyway I am pretty shure that this is the way to go.

Malcolm Frexner