views:

860

answers:

3

I have a LINQ to SQL generated class with a readonly property:

<Column(Name:="totalLogins", Storage:="_TotalLogins", DbType:="Int", UpdateCheck:=UpdateCheck.Never)>  _
Public ReadOnly Property TotalLogins() As System.Nullable(Of Integer)
    Get
     Return Me._TotalLogins
    End Get
End Property

This prevents it from being changed externally, but I would like to update the property from within my class like below:

Partial Public Class User

...

    Public Shared Sub Login(Username, Password)
     ValidateCredentials(UserName, Password)

     Dim dc As New MyDataContext()
     Dim user As User = (from u in dc.Users select u where u.UserName = Username)).FirstOrDefault()
     user._TotalLogins += 1
     dc.SubmitChanges()
    End Sub

...

End Class

But the call to user._TotalLogins += 1 is not being written to the database? Any thoughts on how to get LINQ to see my changes?

A: 
Make a second property that is protected or internal(?) 

<Column(Name:="totalLogins", Storage:="_TotalLogins", DbType:="Int", UpdateCheck:=UpdateCheck.Never)>  _
protected Property TotalLogins2() As System.Nullable(Of Integer)
    Get
        Return Me._TotalLogins
    End Get
    Set(byval value as System.Nullable(Of Integer))
        Return Me._TotalLogins
    End Get
End Property

and then update that . I think it won't save readonly properties by default. And why should it anyway. I now it's a hack but hey that's life.

chrissie1
+2  A: 

Set the existing TotalLogins property as either private or protected and remove the readonly attribute. You may also want to rename it e.g. InternalTotalLogins.

Then create a new property by hand in the partial class that exposes it publically as a read-only property:

Public ReadOnly Property TotalLogins() As System.Nullable(Of Integer)
    Get
        Return Me.InternalTotalLogins
    End Get
End Property
DamienG
A: 

Before you change the field call SendPropertyChanging() and then after call SendPropertyChanged(""). This will make the Table entity tracking know something changed.

Andrew Davey