Skip to content

Instantly share code, notes, and snippets.

@DominicFinn
Last active January 21, 2016 21:24
Show Gist options
  • Save DominicFinn/390d3b854b7d22a03fe5 to your computer and use it in GitHub Desktop.
Save DominicFinn/390d3b854b7d22a03fe5 to your computer and use it in GitHub Desktop.
Methods of dealing with ado.net datatables
Imports System.Data.SqlClient
Imports DataAccess.Console
Module Program
Sub Main()
dim table = new DataTable
Using connection As New SqlConnection("Initial Catalog=robotdatabase;Data Source=localhost;integrated security=SSPI")
connection.Open()
Using command As New SqlCommand("select id, name, strength, intelligence from robots", connection)
Using dataAdapter As New SqlDataAdapter(command)
dataAdapter.Fill(table)
End Using
End Using
connection.Close()
End Using
' the most basic, nice and fast but we aren't writing real time systems. The speed is of no benefit in todays world.
' What is 100x more expensive is the lack of maintainability and the obfuscation of any business logic
'that may be applied (ie dataRow(0) + dataRow(1))
For Each row As DataRow In table.Rows
System.Console.WriteLine("Name: {0}, Total Power: {1}", row(1), row(2) + row(3))
Next
' a little better, this can still be useful in some situations, however, from a testing perspective,
'unit testing datatables is still a nightmare
' so this leads to unmaintainable code again. Also, if the datatable is used in multiple places or
'passed around the column references need to be maintained everywhere
For Each row As DataRow In table.Rows
System.Console.WriteLine("Name: {0}, Total Power: {1}", row("name"), row("strength") + row("intelligence"))
Next
' the preferred method, transfer the datatable into an object at the earliest possible time (dataaccess/database layer).
' It's then a single point of maintenance and the business#
' logic makes considerably more sense
dim robots = table.Rows.Cast(of DataRow).Select(Function(row)
Return New Robot with {
.Id = row.GetInt("id"),
.Name = row.GetString("name"),
.Strength = row.GetInt("strength"),
.Intelligence = row.GetInt("intelligence")
}
End Function)
For Each robot In robots
System.Console.WriteLine("Name: {0}, Total Power: {1}", robot.Name, robot.TotalPower)
Next
System.Console.ReadKey()
End Sub
End Module
Class Robot
Property Id As String
Property Name As string
Property Strength As Integer
Property Intelligence As Integer
ReadOnly Property TotalPower() As Integer
Get
Return Me.Strength + me.Intelligence
End Get
End Property
End Class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment