Search code examples
petapoco

Assigning Private Property values


I'm testing out PetaPoco to determine if it meets our needs. I was under the impression that it would delve into my class and see the private properties that I've marked up as valid columns. Unfortunately, it's not behaving as expected. Can you please take a look and let me know if I'm doing something wrong.

My test class:

Imports PetaPoco

<PetaPoco.TableName("PaulTest")>
<PetaPoco.PrimaryKey("ID")>
Public Class PaulTest

    <PetaPoco.Column("ID")>
    Private Property pvtID As Integer
    Private pvtName As String

    Private Sub New()

    End Sub

    Public Sub New(name As String)
        If String.IsNullOrEmpty(name) Then
            Throw New ArgumentException("Passed Name is empty")
        End If

        Me.pvtName = name

    End Sub

    <PetaPoco.Ignore>
    Public ReadOnly Property ID As Integer
        Get
            Return pvtID
        End Get
    End Property

    <PetaPoco.Column("Name")>
    Public Property Name As String
        Get
            Return pvtName
        End Get
        Set(value As String)
            If String.IsNullOrEmpty(value) Then
                Throw New ArgumentException("Passed Name is empty")
            End If

            Me.pvtName = value
        End Set
    End Property

End Class

The call to the DB (_db is a PetaPoco database object)

Return (_db.Fetch(Of Peta.Domain.PaulTest)(";EXEC selAllPaulTest")).OrderBy(Function(PaulTest) (PaulTest.ID)).ToList()

What's in the database

ID  Name
107 Paul

What's being returned:

PaulTest.ID = 0
PaulTest.pvtID = 0
PaulTest.Name = "Paul"
PaulTest.pvtName = "Paul"

Solution

  • <PetaPoco.Ignore> attribute instructs PetaPoco to ignore the column during mapping. As such, the property Id will always be returning the default value of 0.

    If you want to prevent the Id property from being modified, comment our or delete the attribute and add a private setter to the Id property as in the following code snippet.

    ' <PetaPoco.Ignore>
        Public Property Id As Integer
            Get
                Return pvtID
            End Get
            Private Set(value As Integer)
                pvtID = value
            End Set
        End Property