如何修改ReadOnly Linq属性

时间:2020-03-06 14:22:48  来源:igfitidea点击:

我有一个LINQ to SQL生成的类,具有只读属性:

<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

这样可以防止在外部进行更改,但是我想从我的类中更新属性,如下所示:

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

但是对user._TotalLogins + = 1的调用未写入数据库吗?关于如何让LINQ看到我的更改有任何想法吗?

解决方案

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

然后更新它。我认为默认情况下它不会保存只读属性。以及为什么要这样。我现在这是一个hack,但这就是生命。

将现有的TotalLogins属性设置为private或者protected,然后删除readonly属性。我们可能还想重命名它,例如InternalTotalLogins。

然后在分部类中手动创建一个新属性,将其公开为只读属性:

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

在更改字段之前,请先调用SendPropertyChanging(),然后在调用SendPropertyChanged("")之后。
这将使Table实体跟踪知道某些更改。