c# - 从 SQL Server 中的 SELECT 获取 bool 值到 C# 中的 bool 值?

标签 c# asp.net sql-server

我的 SELECT 中有这段代码:

SELECT  A.CompletedDate,
    CASE
        WHEN (@AdminTestId IS NULL AND @UserTestId IS NULL) THEN 0
        WHEN (@AdminTestId = temp.AdminTestId AND @UserTestId = A.UserTestId) THEN 1
        WHEN (@AdminTestId = temp.AdminTestId AND @UserTestId IS NULL) THEN 1
    ELSE 0
    END AS [Current], 

在我的 ASP.NET DTO 中我有:

public partial class GetTestsDTO
{
    public bool? GradePass { get; set; }
    // the following line is what is giving the error. If I remove
    // the line it will not try to convert the data and there is no
    // error. Note that I want to put this into a bool as web.api
    // then passes it to the client as a bool
    public bool Current { get; set; } 
    public DateTime? CompletedDate { get; set; }
}

它给我一个错误,我将不胜感激。

错误是:

message=The specified cast from a materialized 'System.Int32' type to the 'System.Boolean' type is not valid.

最佳答案

最简单的方法(SQL Server 端)是将值 01 转换为 BIT数据类型:

SELECT  A.CompletedDate,
  CASE
    WHEN (@AdminTestId IS NULL AND @UserTestId IS NULL) 
    THEN CAST(0 AS BIT)
    WHEN (@AdminTestId = temp.AdminTestId AND @UserTestId = A.UserTestId) 
    THEN CAST(1 AS BIT)
    WHEN (@AdminTestId = temp.AdminTestId AND @UserTestId IS NULL) 
    THEN CAST(1 AS BIT)
   ELSE CAST(0 AS BIT)
  END AS [Current], 

或一次完整的表达:

SELECT  A.CompletedDate,
    CAST((CASE
         WHEN (@AdminTestId IS NULL AND @UserTestId IS NULL) THEN 0
         WHEN (@AdminTestId = temp.AdminTestId AND @UserTestId = A.UserTestId) THEN 1
         WHEN (@AdminTestId = temp.AdminTestId AND @UserTestId IS NULL) THEN 1
         ELSE 0
         END)
         AS BIT) AS [Current], 

SQL Server Data Type Mappings :

╔═════════════════════════════════╦═════════════════════╦═══════════════════════╗
║ SQL Server Database Engine type ║ .NET Framework type ║ SqlDbType enumeration ║
╠═════════════════════════════════╬═════════════════════╬═══════════════════════╣
║ bit                             ║ Boolean             ║ Bit                   ║
╚═════════════════════════════════╩═════════════════════╩═══════════════════════╝

关于c# - 从 SQL Server 中的 SELECT 获取 bool 值到 C# 中的 bool 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35887649/

相关文章:

c# - Linq 在自动同步的主键字段上插入

c# - 参数化查询需要参数 '@Id' ,但未提供

javascript - 与 CKEditor 3 集成的 ASPNetSpell 拼写检查器不适用于 Chrome

c# - 从 View (.cshtml) 访问 viewbag 值

c# - 将 PDF 文档转换为 XML 文件,最好使用 ITextSharp

asp.net - 无法访问所请求的页面,因为该页面的相关配置数据无效

asp.net - 在ElasticSearch NEST中创建自定义标记生成器

sql - 更改行的排序顺序后如何重新排列 "sort order"列

sql - 根据另一列的值选择特定列

php - 警告 : dbx: module 'mssql' not loaded