如何使用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#中的Int32Int64等效(或分别为intlong

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

  

{“从具体化的'System.Int32'类型到   “ System.Int64”类型无效。“}

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

sadsasafsa 回答:如何使用Database.SqlQuery <>读取Int64和Int32值

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

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

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

"select CONVERT(BIGINT,ISNULL(MAX({primaryKeyFieldName}),-2))"
本文链接:https://www.f2er.com/2863774.html

大家都在问