Using an ObjectDataSource and Business Component - Design Pattern Question
Posted on 2006-11-03
I want to populate a DetailsView with a record from my database.
However I need to perform some conditional logic before passing the data to my ObjectDataSource.
I was wondering the best way to accomplish this. Obviously I cant create a DataReader and pass that back to the ObjectdataSource as I would not be able to perform the conditional logic.
This is how I see it being done
I have to create an object (class) to represent the data held in the record.
Then I need to get the record using ExecuteNonQuery. Then pass some field vales through the condtional statments.
Then save the field values (and revised values) to my object and send them back to the ObjectDataSource.
Here is some code that I've already written
Public Class WeddingPolicyDetails
Public PurchaseID As Integer
Public WeddingDate As DateTime
Public DobAge As String
' etc etc
Public Class PolicyAdmin
Public Function GetWeddingPolicyByID(ByVal purchaseID As String) As WeddingPolicyDetails
' Create the Connection object
Dim connection As New SqlConnection(connectionString)
Dim details As New WeddingPolicyDetails()
' Create and initialize the Command object
Dim selectString = "SELECT WeddingPolicies.wpol_id, WeddingPolicies.wpol_entrydate, WeddingPolicies.wpol_customerid, WeddingPolicies.wpol_weddingdate, WeddingPolicies.wpol_coverlevel, WeddingPolicies.wpol_marquee, WeddingPolicies.wpol_liability, WeddingPolicies.wpol_groomname, WeddingPolicies.wpol_groomdob... etc WHERE (WeddingPolicies.wpol_id = @purchaseID)"
Dim command As SqlCommand = New SqlCommand(selectString, connection)
command.Parameters.AddWithValue("@purchaseID", SqlDbType.Int).Value = purchaseID
' Open the connection and get the data
Dim reader As SqlDataReader = command.ExecuteReader()
' Perform conditional logic...
' If the Date of Birth field does not have a value, use the age field
If reader("wpol_dob") Is DBNull.Value Then
details.DobAge = reader("wpol_age")
' Use the Age field and the Date of Birth field
details.DobAge = reader("wpol_age") & " (Date of Birth: " & reader("wpol_dob") * ")"
' Load the object with values
details.PurchaseID = reader("wpol_id")
details.WeddingDate = reader("wpol_weddingdate")
' Continue loading the object with DataReader values
Catch ex As Exception
' Close the connection and throw the exception
Is this correct? Is there a better way to do it? Doing it this way means I have to spend a fair amount of time creating the WeddingPolicyDetails object.
Perhaps there is a way of interacting with a Datareader object (i.e. get the datareader, amend some values within it and then return the datareader (as opposed to returning the WeddingPolicyDetails object.