Assuming I have an Object Car with one property: Model
I would populate the object using the database as follows:
Public Class Car
Public Property Model() As String
Get
Return _Model
End Get
Set(ByVal value As String)
_Model = value
End Set
End Property
Private _Model As String
Private Sub SetObjectData(ByVal theObjReader As System.Data.SqlClient.SqlDataReader)
Try
Me._Model = theObjReader("Model").ToString()
Catch ex As Exception
Throw New Exception("Unable to Initialize Car.")
End Try
End Sub
Public Sub New(ByVal Car_ID As Integer)
Dim connection As New SqlConnection(DBTool.DataConnectionString)
Try
Dim cmd As SqlCommand
cmd = New SqlCommand("getCarByCar_ID", connection)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@Car_ID ", Car_ID)
connection.Open()
Dim objReader As SqlDataReader = cmd.ExecuteReader()
Do While objReader.Read()
SetObjectData(objReader)
Loop
objReader.Close()
connection.Close()
Catch ex As Exception
connection.Close()
End Try
End Sub
End Class
Now, lets assume for the sake of the argument that this class is wrapped in a DLL.
What I wish to do is to inherit it, while expending my properties. For instance, lets say we want to have a new Object “Expensive_Car” with a new property “Price”.
How can I utilize the previous Car object and initialize this derived class in the most “organized” way without writing code twice? The field “Price” is saved in the same SQL table as the field “Model”. Of course we need to obtain the “Price” from the Database, just like we pulled Model.
My goal is to utilize existing classes and to expend them using new derived classes without changing the parent class at all. The SQL database structure can change using additional fields as needed.
Thanks!
Nick
You might want to consider one of the many ORMs out there like Entity Framework or NHibernate.
If you really want a roll-your-own approach the simplest way from here is probably to add two
protected overridablemethods to the base class, one to create the SqlCommand object with the correct stored proc name and the other to load properties specific to derived classes.You should probably also wrap the creation of connection, command and data reader objects in
Usingstatements to make sure everything gets cleaned up correctly.Here’s a c# example because my VB.Net is really rusty:
It won’t compile but should give you the idea. You want to make just the parts that can change overridable – calling a different stored proc and loading the properties specific to the derived class.