我有一个函数可以检查我的数据库以查看记录是否已经存在。如果记录确实存在,则返回该记录的 id,如果不存在,则创建新记录并返回新 id。
Friend Shared Function GetLogType(LogType As String, Optional Description As String = "")
If GlobalVar.db.users.References.Count(Function(t) t.Description = LogType And t.DescriptionLong = Description) > 0 Then
Return GlobalVar.db.users.References.First(Function(t) t.Description = LogType And t.DescriptionLong = Description).RefID
Else
Dim Ref As New Reference
Ref.RefTypeID = 2
Ref.Description = LogType
Ref.DescriptionLong = Description
Ref.Active = True
Ref.CreateDate = Now
Ref.UpdatedDate = Now
GlobalVar.db.users.Entry(Ref).State = EntityState.Added
GlobalVar.db.users.SaveChanges()
Return GlobalVar.db.users.References.First(Function(t) t.Description = LogType And t.DescriptionLong = Description).RefID
End If
End Function
该函数检查数据库中的两个字段以验证记录是否存在:Description
和DescriptionLong
。问题是偶尔DescriptionLong
允许NULL
在数据库中,但是我的函数会自动返回一个值""
forDescriptionLong
在数据库中,但是我的函数在保存新记录时
我试图让函数输入一个NULL
值并通过执行以下操作检查一个NULL
值:
Friend Shared Function GetLogType(LogType As String, Optional Description As String = "")
Dim DescVal As String
If Description = "" Then
DescVal = Nothing
Else
DescVal = Description
End If
If GlobalVar.db.users.References.Count(Function(t) t.Description = LogType And t.DescriptionLong = Description) > 0 Then
Return GlobalVar.db.users.References.First(Function(t) t.Description = LogType And If(DescVal = Nothing, 1 = 1, t.DescriptionLong = DescVal)).RefID
Else
Dim Ref As New Reference
Ref.RefTypeID = 2
Ref.Description = LogType
Ref.DescriptionLong = DescVal
Ref.Active = True
Ref.CreateDate = Now
Ref.UpdatedDate = Now
GlobalVar.db.users.Entry(Ref).State = EntityState.Added
GlobalVar.db.users.SaveChanges()
Return GlobalVar.db.users.References.First(Function(t) t.Description = LogType And If(DescVal = Nothing, 1 = 1, t.DescriptionLong = DescVal)).RefID
End If
End Function
但是该函数会忽略NULL
所有值,因此如果DescriptionLong
在NULL
数据库中,它将不会通过第一个 If 语句,并且该函数每次都会创建一条新记录。
基本上我想要的是将可选参数Description
设置为 beNULL
或 be > ""
,并让数据库返回匹配记录的 ID,或者创建新记录。相反,如果DescriptionLong
在NULL
数据库中并且DescVal
是Nothing
函数中,它将每次创建一个新记录,而不管数据库中是否已经存在具有相同值的记录。
我发现的另一个解决方案是,如果我允许函数简单地传递,它确实有效Description
,""
但这并不理想。