Search code examples
c#.netoopdesign-patternsdata-transfer-objects

Data Transfer Objects and Reporting


I have these scenario:

//This class maps to the "Item" table in the database
public class Item
{
   public int itemID { get; set;}
   public string itemName { get; set; }
   public int quantity { get; set; }
}

//Items record are returned from the database as list    
List<Item> items = ItemDAO.GetItems();

I want to generate a report that include aggregate values (from query/Stored Procedure)

ItemID| ItemName | Qty | QtySoldThisMonth | QtySoldThisYr
-----------------------------------------------------------
123   | Vit. C   |  20 |   55             |    400
239   | Maloxin  |  25 |   12             |    210

The Item class does not have these extra fields This would have been easier with datatable which could have varying number of columns but I am using a list

Please, how would I go about this


Solution

  • you can always create another DTO specifically for that aggregated view and use that in your reports.

    A little more general solution than a specific DTO for each view would be to create a DTO for reports on Item and use a collection of fields instead of class properties to store aggregate values in the DTO.

    For instance:

     class AggregatedReportField {
         public string FieldName { get; set; }
         public decimal FieldValue { get; set; }
     }
    
     class ItemReportDTO {
    
         public Dictionary<string, AggregatedReportField> ReportFields { get; private set; }
    
         public ItemReportDTO()
         {
             ReportFields = new Dictionary<string, AggregatedReportField>();
         }
    
         public void Add(AggregatedReportField field)
         {
             if (!ReportFields.ContainsKey(fieldl.FieldName))
                  ReportFields.Add(field.FieldName, field);
         }
     }
    

    in your DAO, you would then first get the values from the database, create AggregatedReportField instances for each value and add them with a name to your DTO. In your report, you would then have to refer to your aggregated values with DTO.ReportFields["SomeValue"].FieldValue.

    the code above is just an example and contains a few bad practices (exposed Dictionary<>).