1

我有一个带有视图和 smallint 字段的 SQL Server 表。视图中的所有数据都会从 Petapoco T4 生成器自动标记为可为空,因为您无法在视图中指定它。到目前为止,我对所有其他数据类型(guid、int、tinyint、string 等)都很好,但似乎可以为空的 smallint 会导致一些问题。

VB.NET 中的 T4 生成器为 SMALLINT 字段创建了这个:

    Private mPasswordResetDays As Integer?
    <Column> _
    Public Property PasswordResetDays() As Integer?
        Get
            Return mPasswordResetDays
        End Get
        Set
            mPasswordResetDays = Value
        End Set
    End Property

但是我收到一个例外:

从 'System.Int16' 转换为 'System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'

在 Petapoco 线 2677:

Line 2675:       else
Line 2676:       {
Line 2677:          converter = src => Convert.ChangeType(src, dstType, null);
Line 2678:       }
Line 2679:            }

从 PetaPoco 执行的 SQL 命令非常简单:

SQL Command: SELECT UserId, AllowPersistentCookie, MinPasswordLenght,
NonAlphanumericPasswordChars, AlphanumericPassword, PasswordResetDays FROM
EVA_vw_UserLoginStatusFromRoles
WHERE UserId = @0 -> @0 [String] = "d85674ab-d389-4548-ad89-5322892ca0e2"

我认为在返回 null 的 ExecuteScalar 命令上已经注意到类似的问题,但行不同,代码也不同。

如果我从整数更改类型?到整数,使它们不可为空,一切正常。

Petapoco 和 SQL Server Smallints 关于这个问题的任何提示?

附录:查看代码为:

SELECT     a.UserId, CAST(MIN(CAST(b.AllowPersistentCookie AS int)) AS bit) AS AllowPersistentCookie, MAX(b.MinPasswordLenght) AS MinPasswordLenght, 
                  CAST(MAX(CAST(b.NonAlphanumericPasswordChars AS int)) AS bit) AS NonAlphanumericPasswordChars, CAST(MAX(CAST(b.AlphanumericPassword AS int)) AS bit) 
                  AS AlphanumericPassword, MIN(b.PasswordResetDays) AS PasswordResetDays
FROM         dbo.EVA_UsersInRoles AS a INNER JOIN
                  dbo.EVA_Roles AS b ON a.RoleId = b.RoleId
WHERE       (DATEDIFF(day, CONVERT(date, GETUTCDATE()), a.StartDate) <= 0) AND (DATEDIFF(day, CONVERT(date, GETUTCDATE()), a.EndDate) >= 0) OR
                  (DATEDIFF(day, CONVERT(date, GETUTCDATE()), a.StartDate) <= 0) AND (a.EndDate IS NULL) OR
                  (DATEDIFF(day, CONVERT(date, GETUTCDATE()), a.EndDate) >= 0) AND (a.StartDate IS NULL) OR
                  (a.EndDate IS NULL) AND (a.StartDate IS NULL)
GROUP BY a.UserId
4

2 回答 2

1

Issue for this plus a solution is at https://github.com/toptensoftware/PetaPoco/issues/153

PetaPoco needs patching with:

- converter = delegate(object src) { return Convert.ChangeType(src, dstType, null); };
+ var underlyingType = Nullable.GetUnderlyingType(dstType) ?? dstType;
+ converter = src => Convert.ChangeType(src, underlyingType, null);

Views are a red herring; you can reproduce this on a concrete table by returning an int NULL column as a uint? or similar.

于 2015-10-16T10:03:12.530 回答
0

它表明您使用表格生成了代码,但现在您正在从视图中获取值。SQL 必须从视图中提示该列不可为空。

于 2013-05-08T16:36:16.517 回答