In my previous post on the MCSF we saw how the Data Access application block can be used to simplify data access. However, once we have retrieved the correct data rows from the database we still need to work with them. We could either pipe them into a dataset and work with them as untyped data, or we could use the Data Mapper application block to convert the data into business objects. The classes in this block are shown in the following image.
For anyone familiar with the work being done on the Linq/Dlinq project the way that the Data Mapping block works will look very similar. We start of by defining our business object and by placing special attributes on the field or properties we want to map to specific columns in the database. In the following code we use fields to keep the code sample short, but they would usually be placed on properties for proper encapsulation:
Public Class Customer
Public Sub New()
End Sub
<DataMapping.DataMap(“Customer Id”, Data.DbType.String, 5)> _
Public CustomerId As String
<DataMapping.DataMap(“Company Name”, Data.DbType.String, 40)> _
Public CompanyName As String
<DataMapping.DataMap(“Contact Name”, Data.DbType.String, 30)> _
Public ContactName As String
End Class
To work with the Data Mapper block we need to create an instance of the DataMapper class. Again this is an abstract class so we need to use the concrete AttributeDataMapper class which provides the implementation details for working with attribute mapped business classes. The DataMapper class supports a method for creating instance(s) of a particular business class. This is illustrated in the following code example:
Dim mapper As DataMapper(Of Customer) = New AttributeDataMapper(Of Customer)
Dim customerSearch As String = “CustomerParameter”
Dim sql As String = “Select * from Customers where [Customer ID] like ” & ds.ParameterName(customerSearch)
Dim para As System.Data.Common.DbParameter = ds.CreateParameter(ds.ParameterName(customerSearch))
Dim reader As Data.Common.DbDataReader = ds.ExecuteReader(sql, para)
Dim list As New List(Of Customer)
list.AddRange(mapper.CreateAllInstances(reader))
reader.Close()
For Each c As Customer In list
MsgBox(c.CompanyName)
Next
Although the Data Mapper block can reduce the code you need to write to populate your business objects, it currently doesn’t support a mechanism for creating, deleting or updating data in the database. It also requires the developer to specify the sql expression used to retrieve the information from the database – since the required columns are all identified by the attributes this code could be automatically generated. In comparison to the Dlinq model that supports class to table mapping attributes, the current DataMapper class is very limited, but could be used to build a much more flexible application block.