在我编写的程序中,当Textbox中有一个空字符串时,它将作为空字符串而不是NULL保存到数据库。
Using DB As New wotcDB
Dim u = (From t In DB.interview_ltu Where t.CONTROL = CONTROL And t.CLIENTCODE = CLIENTCODE).FirstOrDefault
If u Is Nothing Then
Dim i As New interview_ltu
i.CONTROL = CONTROL
i.CLIENTCODE = CLIENTCODE
i.LTUnemp2Years = cboLTUnemp2Years.DBValue
i.LTUnempExhast26wks = cboLTUnempExhast26wks.DBValue
i.LTUComments = txtLTUnemployedCMT.Text
i.LTUnempStart = txtLTUnempStart.DateValue
i.LTUnempStop = txtLTUnempStop.DateValue
DB.interview_ltu.Add(i)
DB.SaveChanges()
Else
u.LTUnemp2Years = cboLTUnemp2Years.DBValue
u.LTUnempExhast26wks = cboLTUnempExhast26wks.DBValue
u.LTUComments = txtLTUnemployedCMT.Text
u.LTUnempStart = txtLTUnempStart.DateValue
u.LTUnempStop = txtLTUnempStop.DateValue
DB.SaveChanges()
End If
End Using
我一直在做这个复杂的步骤,其中,我检查String.IsNullorEmpty每一个,但我觉得这不应该是必要的尤其是考虑到与此相关的在谷歌的问题暗示恰恰相反,人们正在尝试获取空字符串而不是NULL。
那么如何让Text框保存为NULL而不是空字符串?
编辑:
我已将此代码添加到我的上下文中;
Private Const StringType As String = "String"
Private Const SavingState As EntityState = EntityState.Added Or EntityState.Modified
Public Overrides Function SaveChanges() As Integer
'when using on ObjectContext replace 'objectContext' with 'this',
'and override SaveChanges(SaveOptions options) instead:
Dim objectContext = CType(Me, IObjectContextAdapter).ObjectContext
Dim savingEntries = objectContext.ObjectStateManager.GetObjectStateEntries(SavingState)
For Each entry As Object In savingEntries
Dim curValues = entry.CurrentValues
Dim fieldMetadata = curValues.DataRecordInfo.FieldMetadata
Dim stringFields = fieldMetadata.Where(Function(f) f.FieldType.TypeUsage.EdmType.Name = StringType)
For Each stringField As Object In stringFields
Dim ordinal = stringField.Ordinal
Dim curValue = TryCast(curValues(ordinal), String)
If Not curValue Is Nothing AndAlso String.IsNullOrWhiteSpace(curValue) Then ' AndAlso curValue.All(Char.IsWhiteSpace) Then
curValues.SetValue(ordinal, Nothing)
End If
Next
Next
Return MyBase.SaveChanges()
'SaveChanges(options) on ObjectContext
End Function
当它达到“For Each entry As Object in savingEntries”时,它只会跳到最后,因为它不会选择任何条目。我试图改变输入。没有成功。