patternMinor
Get list from database in 3 layer model
Viewed 0 times
layerdatabasegetlistfrommodel
Problem
I'm working on some testing project. For some reason I think I'm doing something wrong with the architecture. I have a simple example to show what I mean.
Database class
PatientDAO
Patient
```
Imports DAO
Imports database_layer
Public Class Patient
Property naam As String
Property lastname As String
Sub New()
End Sub
Sub New(_naam As String, _lastname As String)
naam = _naam
las
Database class
Imports DAO
Imports System.Data.SqlClient
Public Class PatientDB
Dim connectionString As String = "Data Source=GSABBOZMAINPC;Initial Catalog=TestDB;Integrated Security=True"
Public Function GetAllPatientFromDB() As List(Of PatientDAO)
Using connection As New SqlConnection(connectionString)
Dim list As New List(Of PatientDAO)
Dim sqlString As String = "select * from patient ;"
Using Command As New SqlCommand(sqlString, connection)
connection.Open()
Using reader As SqlDataReader = Command.ExecuteReader
While reader.Read
Dim firstName As String = reader("firstnamePT").ToString()
Dim Name As String = reader("naamPT").ToString()
Dim patient As New PatientDAO(Name, firstName)
list.Add(patient)
End While
End Using
Return list
End Using
End Using
End Function
End ClassPatientDAO
Public Class PatientDAO
Private _name As String
Private _lastname As String
Sub New(naam As String, lastname As String)
_name = naam
_lastname = lastname
End Sub
Public ReadOnly Property Name As String
Get
Return _name
End Get
End Property
Public ReadOnly Property Lastname As String
Get
Return _lastname
End Get
End Property
End ClassPatient
```
Imports DAO
Imports database_layer
Public Class Patient
Property naam As String
Property lastname As String
Sub New()
End Sub
Sub New(_naam As String, _lastname As String)
naam = _naam
las
Solution
Well, you were right to think you are wrong. We shouldn't need to instantiate an object with an empty constructor to something like this. This is exactly what the
First, make your
And now we can call the method without instantiating an instance of the class:
And once we've done this, arguably, we may want to eliminate the default, zero-argument constructor.
Shared keyword is for.First, make your
getAllPatientsInList function Shared:Public Shared Function GetAllPatients() As List(Of Patient)
' method implementation
End FunctionAnd now we can call the method without instantiating an instance of the class:
For Each item as Patient in Patient.GetAllPatients()
' do something with item
NextAnd once we've done this, arguably, we may want to eliminate the default, zero-argument constructor.
Code Snippets
Public Shared Function GetAllPatients() As List(Of Patient)
' method implementation
End FunctionFor Each item as Patient in Patient.GetAllPatients()
' do something with item
NextContext
StackExchange Code Review Q#95016, answer score: 8
Revisions (0)
No revisions yet.