我遇到错误:未为类型“User”和“Integer”定义运算符“>”,并且“User”类型的值无法转换为“Integer”。
我的代码有问题吗?
谢谢
Dim userid = uService.GetUserById(CInt(lblid.Text))
If userid > 0 Then 'this line error
End If
Public Function GetUserById(ByVal UserNo As Integer) As User
Dim sql = $"SELECT * FROM Users WHERE id = {UserNo}"
Using _conn = New OleDbConnection(DbContext.GetOledbConnectionString())
Return _conn.Query(Of User)(sql).FirstOrDefault()
End Using
End Function
GetUserById
返回一个用户,如果该用户存在,则 Nothing
否则(因为 .FirstOrDefault()
)。
不要检查用户 id > 0 的结果,而是检查
Nothing
的结果
Dim user = uService.GetUserById(CInt(lblid.Text))
If user IsNot Nothing Then
' Do something with user
End If
更安全的方法是检查用户输入是否是有效整数:
Dim userId As Integer
If Integer.TryParse(lblid.Text, userId) Then
Dim user = uService.GetUserById(userId)
If user IsNot Nothing Then
' Do something with user
End If
End If