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

How can I read both Int64 and Int32 values using Database.SqlQuery<>

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

如果找不到具有给定 ID 的记录,我创建的在数据库上执行的查询将 return -2,如果找到项目,则 return 其 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# 中的 Int32Int64分别(或分别为 intlong)。

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

{"The specified cast from a materialized 'System.Int32' type to the 'System.Int64' type is not valid."}

虽然可以将 int 存储在 long 变量中,但在 Database.SqlQuery 中将 Int32 转换为 Int64 会导致此异常。 我想知道这种情况是否有任何解决方法,或者我只需要使用 SqlDataReader.ExecuteReader?

读取值

在查询中将 PK 转换为 BIGINT 并读取为 Int64:

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

此外,您可以将 COALESCE 替换为 ISNULL 函数:

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