强类型数据集的继承和NullValue问题

时间:2011-08-12 15:10:45

标签: asp.net vb.net asp.net-3.5 strongly-typed-dataset

在以下情况中,处理强类型数据集的Null值的最简单/最干净/最简单/最好的方法是什么:

  • 基类具有通过其构造函数
  • 设置的Nullable值
  • 派生类的构造函数具有强类型DataSet Row作为参数,并且在访问空值时抛出异常。

这里有一个简化的例子来说明我面临的问题。与您的代码有任何相似之处纯属巧合     

Public MustInherit Class BaseClass
     Private _Number as Nullable(of integer)
     Public Sub New(Number as Nullable(of integer))
         _Number = Number 
     End Sub
End Class

Public Class DerivedClass
    Inherits BaseClass

    'Throw System.Data.StrongTypingException "The value for column 'Number'
    'in table 'SomeData' is DBNull." when Number is null
    Public Sub New(DataRow as my DataDLL.SomeDataRow)
          MyBase.New(DataRow.Number) 
    End Sub

    'First statement of this 'Sub New' must be a call to 'MyBase.New' 
    'or 'MyClass.New' because base class 'BaseClass' of 'DerivedClass' 
    'does not have an accessible 'Sub New' that can be called with no arguments
    Public Sub New(DataRow as my DataDLL.SomeDataRow)
         If TermRow.IsNumberNull() Then 
              MyBase.New(Nothing)
         Else
              MyBase.New(DataRow.Number )
         End If
    End Sub  

    'Also Throw System.Data.StrongTypingException because As part of preparing 
    'the argument list for the call to IIf, the Visual Basic compiler calls 
    'every function in every expression.  
    Public Sub New(DataRow As MyData)
        MyBase.New(DirectCast(IIf(DataRow.IsNumberNull(), _
                                  Nothing, _
                                  TermRow.Number), Nullable(Of Integer)))
    End Sub

End Class

我只放了3 Public Sub New来展示我考虑过的3个替代方案。

1 个答案:

答案 0 :(得分:1)

这是有道理的,您必须检查DBNull,这与Integer?

不同

而不是IIF,请尝试IF Operator,这是.NET 3.5的新手。您还必须将Nothing转换为Nullable(Of Integer),因为If函数将返回0;否则;返回值的返回类型基于true-part和false-part的on the wider of the types来确定。

Public Sub New(DataRow As MyData)
    MyBase.New(If(DataRow.IsNumberNull(), _
                  DirectCast(Nothing, Nullable(Of Integer)), _
                  DataRow.Number))
End Sub