简体   繁体   English

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

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

I've wrote a function to check if specific ID exist in a table using schema name and name of table as input parameters.我编写了一个函数来检查表中是否存在特定 ID,使用模式名称和表名称作为输入参数。

Query which I created to execute on database will return -2 if it cannot find record with given ID and return its ID if item is found.我创建的在数据库上执行的查询如果找不到具有给定 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;
}

My Problem is that some primary keys in my database are of type Int and some are of type BigInt which are equivalent to Int32 and Int64 in C# respectively (or int and long respectively).我的问题是我的数据库中的一些主键是Int类型,一些是BigInt类型,它们分别相当于 C# 中的Int32Int64 (或分别是intlong )。

When I read primary keys of tables of type BigInt nothing wrong happens but when I want to read primary keys of table which are of type Int it causes exception:当我读取 BigInt 类型的表的主键时,没有发生任何错误,但是当我想读取 Int 类型的表的主键时,它会导致异常:

{"The specified cast from a materialized 'System.Int32' type to the 'System.Int64' type is not valid."} {"从具体化的 'System.Int32' 类型到 'System.Int64' 类型的指定转换无效。"}

Although it is possible to store int in long variables, casting Int32 to Int64 in Database.SqlQuery causes this exception.尽管可以将 int 存储在 long 变量中,但在Database.SqlQuery中将Int32Int64会导致此异常。 I want to know are there any workarounds for this situation or I only have to read values using SqlDataReader.ExecuteReader ?我想知道这种情况是否有任何解决方法,或者我只需要使用SqlDataReader.ExecuteReader读取值?

Convert PK to BIGINT in query and read as Int64 :在查询中将 PK 转换为BIGINT并读取为Int64

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

Also, you can replace COALESCE with ISNULL function:此外,您可以用ISNULL函数替换COALESCE

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM