【问题标题】:Inserting NULL integer using VB.Net and EF5使用 VB.Net 和 EF5 插入 NULL 整数
【发布时间】:2017-04-06 14:41:11
【问题描述】:

处理依赖于旧版本实体的应用程序,我正在尝试将NULL 插入int 字段。 SQL Server 中的字段是(int, null)

这是 EF 中对象的定义:

<EdmScalarPropertyAttribute(EntityKeyProperty:=false, IsNullable:=true)>
<DataMemberAttribute()>
Public Property application_id() As Nullable(Of Global.System.Int32)

...这是我要设置的地方:

applications.application_id = IIf(IsNumeric(txtAppID.Text), CInt(txtAppID.Text), Nothing)

响应中抛出的错误是:

“System.InvalidCastException”类型的异常发生在...中,但未在用户代码中处理

附加信息:指定的演员表无效。

我可以确认这个问题是由于 Nothing 部分而引发的,因为之前它是 applications.application_id = CInt(txtAppID.Text) 并且一切都很好。

我试过DBNull.Value 而不是Nothing,尽管错误读取相同。尽管大多数问题都与 ES6 或 datetime 字段相关,但我还是做了一些研究,因此我觉得我的问题足够具体,可以提出自己的问题。

谢谢。

【问题讨论】:

  • 更改代码以便仅在记录中添加数值,即:If IsNumeric(txtAppID.Text) Then applications.application_id = CInt(txtAppID.Text)
  • @LaughingVergil 我应该提到这也用于更新。使用该方法意味着用户无法删除应用程序 ID,因为如果他们清空该字段并更新,applications.application_id 将不会被设置。

标签: sql-server vb.net entity-framework


【解决方案1】:

IIf 函数不会短路,因此总是同时评估真假部分,因此在这种情况下它不起作用。 If 关键字确实短路,但您可能会遇到返回类型和可为空值类型的问题(例如,Dim x As Integer? = If(False, 1, Nothing) 导致 x = 0,因为 If 返回 Integer 而不是 Integer?) .

所以,我建议使用常规的If 语句:

If IsNumeric(txtAppID.Text) Then
    applications.application_id = CInt(txtAppID.Text)
Else
    applications.application_id = Nothing
End If

或者你可以创建一个辅助函数:

Function NullableCInt(value As String) As Integer?
    If IsNumeric(value) Then Return CInt(value)
    Return Nothing
End Function

并使用它:

applications.application_id = NullableCInt(txtAppID.Text)

【讨论】:

  • 欣赏它,多么令人讨厌的疏忽!我通过简单地做Dim AppID as Integer? = IIf(IsNumeric(txtAppID.Text), txtAppID.Text, Nothing)applications.application_id = AppID 来修复它,它似乎工作得很好。
  • 您可能想转为 Option Strict On,这将不允许像这样的隐式转换,但会产生更健壮的代码。
  • 正确,我很快就说我的方法在测试所有案例之前都有效。我实际上真的很喜欢 Fabio 的解决方案,但是您的解决方案同样正确。感谢您的意见,并带领我朝着正确的方向前进。
  • @Santi 是的,尤其是@Fabio 对TryParse 的性能优化非常好,所以我要借用它来编写自己的代码! :-)
【解决方案2】:

您可以使用 If 方法进行强制转换

Dim temp As Integer
applications.application_id = If(Integer.TryParse(value, temp), temp, DirectCast(Nothing, Integer?))

为了更好的可读性,您可以引入“默认”值

Static DEFAULT_VALUE As Integer? = Nothing    
Dim temp As Integer
applications.application_id = If(Integer.TryParse(value, temp), temp, DEFAULT_VALUE)

使用Integer.TryParse,您只需将字符串“检查/转换”一次即可。

【讨论】:

    猜你喜欢
    • 2011-09-22
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-14
    相关资源
    最近更新 更多