开发者社区> 问答> 正文

如何使用Database.SqlQuery <>读取Int64和Int32值

我编写了一个函数,使用模式名称和表名称作为输入参数来检查表中是否存在特定的ID。

我创建要在数据库上执行的查询,如果找不到具有给定ID的记录,将返回-2,如果找到item,则返回其ID。

private long isThisNodeAlreadyInsertedInDatabaseByHeadquarter(
    string schemaName
    string tableName,
    string primaryNodeId,
    string primaryKeyFieldName){

    string targetTableName = $"{schemaName}.{tableName}";
    string sqlCommandString2 = $"select COALESCE(MAX({primaryKeyFieldName}),-2)" + " " + Environment.NewLine +
                             $"from {targetTableName}" + " " + Environment.NewLine +
                              "WHERE " + " " + Environment.NewLine +
                               $"{primaryKeyFieldName}={foundID}";
    //will return -2 if not found otherwise return its id
    DbRawSqlQuery<Int64> result2 = rawDbContext.Database.SqlQuery<Int64>(sqlCommandString2);
    long foundID = result2.Single();
    return foundID;
}

我的问题是,在我的数据库中的某些主键类型的Int,有些是类型的BigInt,其等效于Int32和Int64 分别(或在C#int和long分别地)。

当我读取BigInt类型的表的主键时,不会发生任何错误,但是当我想要读取Int类型的表的主键时,会导致异常:

{“从实例化的“ System.Int32”类型到“ System.Int64”类型的指定强制转换无效。”}

尽管可以将int存储在长变量中,但强制转换Int32为Int64in Database.SqlQuery会导致此异常。我想知道是否有针对这种情况的解决方法,或者我只需要使用读取值SqlDataReader.ExecuteReader?

展开
收起
心有灵_夕 2019-12-25 21:53:04 1179 0
1 条回答
写回答
取消 提交回答
  • 将PK转换为BIGINTin查询,并读取为Int64:

    "select CONVERT(BIGINT,COALESCE(MAX({primaryKeyFieldName}),-2))"
    
    

    另外,您可以COALESCE用ISNULL函数替换:

    "select CONVERT(BIGINT,ISNULL(MAX({primaryKeyFieldName}),-2))"
    
    2019-12-25 21:53:24
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spark SQL: Past, Present and Future 立即下载
Spark SQL:Past Present &Future 立即下载
Tracking-Ransomware-End-To-End 立即下载