C# Model Object For a Report
I am generating a report from a stored proc that outputs a DataTable in the following format:
id | date | value
--------------------------
0 | 5/18/11 | 10
0 | 5/19/11 | 13
0 | 5/20/11 | 7
0 | 5/21/11 | 1
1 | 5/18/11 | 9
1 | 5/19/11 | 34
1 | 5/20/11 | 5
1 | 5/21/11 | 6
where the id corresponds to an employee's id number.
I don't like dealing with raw DataTables throughout my code, but I don't know the best way to represent such information most effectively in some sort of model object in C#. How would you do开发者_C百科 it?
Simply make a class...
public class ReportModel
{
public int ID {get; private set;}
public DateTime Date {get; private set;}
public int Value {get; private set;}
private ReportModel() {}
public static ReportModel FromDataRow(DataRow dataRow)
{
return new ReportModel
{
ID = Convert.ToInt32(dataRow["id"]),
Date = Convert.ToDateTime(dataRow["date"]),
Value = Convert.ToInt32(dataRow["value"])
};
}
public static List<ReportModel> FromDataTable(DataTable dataTable)
{
var list = new List<ReportModel>();
foreach(var row in dataTable.Rows)
{
list.Add(ReportModel.FromDataRow(row);
}
return list;
}
}
You can also use AutoMapper to encapsulate the mapping from DataRow to ReportModel.
Take a look at this thread, How to create CSV Excel file C#?
精彩评论