I'm using the following function to map columns from a DataTable (passed from the data tier) to object properties. The function exists within the class I'm populating. The class has two methods: Load() which loads the object with values and LoadAll() which returns a collection of populated objects. I wanted to be able to use the same code to populate the current object or a new object. However I'm less than happy with the result, largely because of the duplication which is a bit of a maintenance nightmare.
Private Function MapDataRowToProperties(ByVal dr As DataRow, ByVal target As Incident) As Incident
If target.Equals(Me) Then
Me.ID = Convert.ToInt32(dr.Item("pkIncidentID"))
Me.Description = dr.Item("IncidentDetail").ToString
Me.Created = Convert.ToDateTime(dr.Item("CreatedOn"))
...
Return Me
Else
Dim NewIncident As New Incident
NewIncident.ID = Convert.ToInt32(dr.Item("pkIncidentID"))
NewIncident.Description = dr.Item("IncidentDetail").ToString
NewIncident.Created = Convert.ToDateTime(dr.Item("CreatedOn"))
...
Return NewIncident
End If
End Function
Note: I'm well aware of ORM tools which will do this for me and I normally use EntitySpaces, but for this project I am unable to do so.