0

Currently, I have a datatable and use a ForEach to loop over it and build objects to add to my list, List<MyClass>.

Unfortunately, this approach requires a separate method for each type just to handle the column mappings. The columns in the datatable DO NOT have the same names as the object properties.

How can I create a generic method to achieve the column mapping? Ideally something like a generic BuildObjects<T> method that can handle BuildObjects<Car>, BuildObjects<Dog> and BuildObjects<Tree> and map the row column to the object property.

DenaliHardtail
  • 27,362
  • 56
  • 154
  • 233
  • 1
    Is there a reason you're not using a pre-existing ORM? because that's basically what they do – Zipper Sep 29 '15 at 15:39
  • There are many reasons we're not using an ORM and none are within my control. – DenaliHardtail Sep 29 '15 at 15:40
  • reflection with a map? – austin wernli Sep 29 '15 at 15:41
  • @austinwernli Any links or additional details? – DenaliHardtail Sep 29 '15 at 15:44
  • @DenaliHardtail You could create custom attributes to place on the object properties of your classes (these could contain the column mapping to the database column). Then you could use reflection to get all properties that have an attribute on them, and create that object using the mappings provided on your properties. Hopefully that idea made some bit of sense – austin wernli Sep 29 '15 at 18:16

2 Answers2

1

Well, BuildObjects would not be generic since the implementation is different for each type.

A better approach would be to have methods like BuildCar ,BuildTree and BuildDog. Then you can loop through your data table and call the appropriate method based on whatever data in the table tells you what the output type is.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • Why could it not be the same for each type? – austin wernli Sep 29 '15 at 19:05
  • @austinwernli Because each type has different fields and different mapping logic. You _could_ try to use completely generic code using reflection, etc. but in the end each type will be mapped differently. – D Stanley Sep 29 '15 at 19:50
0

You could define attributes on the object properties of your classes. (These could contain the column mapping to the database column name). From there you could get all properties of that class with the defined attribute like:

How to get a list of properties with a given attribute?

which then you could use reflection to create the objects with the desired values.

Community
  • 1
  • 1
austin wernli
  • 1,801
  • 12
  • 15