Performing Reflection on Objects

Hey Everyone

What I'm trying to do is create a SQL read procedure that I can reuse. My initial idea was to create the procedure that gets passed an object.

ie. Private Sub SqlRead(ByRef Request As Object)

The reason I would need reflection is to analyze the object for members of type String whose name starts with DB.

ie. Public Class Employee
Public DBFirstName, DBLastName as String

When that object is passed to the procedure, the SQL command text would be created dynamically according what members are in the object. Do I require reflection for this or is there another way

Bascially by the end of it, I want the procedure to execute the command below if it were passed that object.j
Select (DBFirstName, DBLastName) from employee


Answer this question

Performing Reflection on Objects

  • cipcip

    Hopefully the enclosed will get you started.

    This function takes any reference type and creates a sql select string for all properties that have a get section (compiler creates a get_XXX method behind the scenes) and starts with DB.

    The table name is the type name ... ie pass a class called Employee into the procedure to get a Select From Employee statement)

    Richard

    Private Function SqlRead(Of T As Class)(ByVal Request As T) As String

    Dim sql As String = "SELECT {0} FROM {1}"

    Dim props As New System.Text.StringBuilder

    For Each mi As Reflection.MemberInfo In Request.GetType.GetMembers

    If mi.MemberType = Reflection.MemberTypes.Method Then

    Dim name As String = mi.Name

    If name.StartsWith("get_DB") Then

    props.AppendFormat("{0}, ", name.Substring(4, name.Length - 4))

    End If

    End If

    Next

    If props.Length <= 0 Then Return Nothing

    Dim propLst As String = props.ToString

    sql = String.Format(sql, propLst.Substring(0, propLst.Length - 2), t.Name)

    Return sql

    End Function


  • Shameer A U

    Thanks for your reply. Thats exactly what I needed Donny.

    I had been reading up a bit on reflection but I couldn't figure out how to perform reflection on an object, only assemblies. Thanks alot.

  • Performing Reflection on Objects