HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Recursive database actions

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
databaserecursiveactions

Problem

I am been using a code pattern for recursive database actions in my applications.

I create two class objects of a database table, singular one (e.g Agent) for holding single record with all fields definition, plural one (e.g Agents) for database actions of that records like, select, insert, delete, update etc. I find it easy using the code pattern.

But as the time runs I find it somewhat laborious to define same database action functions in different classes only differing in datatype.

How can I make it good and avoid defining it again and again?

Sample code of a class file representing the class definition:

`Imports EssenceDBLayer

Public Class Booking
#Region "Constants"
Public Shared _Pre As String = "bk01"
Public Shared _Table As String = "bookings"
#End Region

#Region " Instance Variables "
Private _UIN As Integer = 0
Private _Title As String = ""
Private _Email As String = ""
Private _contactPerson As String = ""
Private _Telephone As String = ""
Private _Mobile As String = ""
Private _Address As String = ""
Private _LastBalance As Double = 0
#End Region

#Region " Constructor "
Public Sub New()
'Do nothing as all private variables has been initiated'
End Sub

Public Sub New(ByVal DataRow As DataRow)
_UIN = CInt(DataRow.Item(_Pre & "UIN"))
_Title = CStr(DataRow.Item(_Pre & "Title"))
_Email = CStr(DataRow.Item(_Pre & "Email"))
_contactPerson = CStr(DataRow.Item(_Pre & "contact_person"))
_Telephone = CStr(DataRow.Item(_Pre & "Telephone"))
_Mobile = CStr(DataRow.Item(_Pre & "Mobile"))
_Address = CStr(DataRow.Item(_Pre & "Address"))
_LastBalance = CDbl(DataRow.Item(_Pre & "Last_Balance"))
End Sub
#End Region

#Region " Properties "
Public Property UIN() As Integer
Get
Return _UIN
End Get
Set(ByVal value As Integer)
_UIN = value
End Set
End Property

Public Property

Solution

What you're talking about is called object-relational mapping.

You could do this, but it will be a fair amount of effort. Luckily many people have run into this same question before, answered it and open-sourced that solution. I suggest looking at using one of those solutions.

nHibernate is just one example but is a popular and mature solution.

Edit: More accurately, object-relational mapping is mapping fields to columns, objects to tables and object relationships to table relationships, so it does exactly what you want and (optionally) much more.

Context

StackExchange Code Review Q#984, answer score: 5

Revisions (0)

No revisions yet.