c# - 如何使用 Database.SqlQuery<> 读取 Int64 和 Int32 值
问题描述
我编写了一个函数来使用模式名称和表名称作为输入参数来检查表中是否存在特定 ID。
如果找不到具有给定 ID 的记录,我创建的要在数据库上执行的查询将返回 -2,如果找到项目,则返回其 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
分别相当于 C# 中的和(或Int32
分别)。Int64
int
long
当我读取 BigInt 类型的表的主键时,没有任何错误发生,但是当我想读取 Int 类型的表的主键时,它会导致异常:
{“从物化 'System.Int32' 类型到 'System.Int64' 类型的指定转换无效。”}
尽管可以将 int 存储在 long 变量中,但转换Int32
为Int64
inDatabase.SqlQuery
会导致此异常。我想知道这种情况是否有任何解决方法,或者我只需要使用读取值SqlDataReader.ExecuteReader
?
解决方案
将 PK 转换为BIGINT
in 查询并读取为Int64
:
"select CONVERT(BIGINT,COALESCE(MAX({primaryKeyFieldName}),-2))"
此外,您可以COALESCE
用ISNULL
函数替换:
"select CONVERT(BIGINT,ISNULL(MAX({primaryKeyFieldName}),-2))"
推荐阅读
- javascript - 我在会话中做错了什么?
- php - 如何随机化 json
- grpc-java - 错误:协议失败:google/protobuf/wrappers.proto:找不到文件。(Maven 构建中的错误)
- c# - 带有实体框架 dbcontext 的 Singleton 好吗?
- python - 检查 Dataframe 是否为空并打印结果
- php - woocommerce 创建具有多项选择的复选框
- authentication - 如果在 drupal 7.x 中更改密码,则删除 uid 的所有会话
- c# - 如何在没有 Application 类或不覆盖它的项目中正确使用 WPF Prism?
- c++ - C++ 属性名称应该用双下划线包裹吗?
- c# - 使用 AutoMapper 将多个对象映射到一个对象