-1

我有一个函数可以检查我的数据库以查看记录是否已经存在。如果记录确实存在,则返回该记录的 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

该函数检查数据库中的两个字段以验证记录是否存在:DescriptionDescriptionLong。问题是偶尔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所有值,因此如果DescriptionLongNULL数据库中,它将不会通过第一个 If 语句,并且该函数每次都会创建一条新记录。

基本上我想要的是将可选参数Description设置为 beNULL或 be > "",并让数据库返回匹配记录的 ID,或者创建新记录。相反,如果DescriptionLongNULL数据库中并且DescValNothing函数中,它将每次创建一个新记录,而不管数据库中是否已经存在具有相同值的记录。

我发现的另一个解决方案是,如果我允许函数简单地传递,它确实有效Description""但这并不理想。

4

1 回答 1

1

试试这个::

GlobalVar.db.users.References.First(Function(t) 
    t.Description = LogType And 
    t.DescriptionLong = If(DescVal = Nothing, t.DescriptionLong, DescVal)).RefID

这将解决您的问题。

于 2013-10-20T05:27:38.337 回答