C# 如何使用Database.SqlQuery读取Int64和Int32值
我编写了一个函数,使用模式名和表名作为输入参数,检查表中是否存在特定ID 若我创建的要在数据库上执行的查询找不到具有给定ID的记录,它将返回-2,若找到项,则返回其IDC# 如何使用Database.SqlQuery读取Int64和Int32值,c#,sql-server,entity-framework,ado.net,dbcontext,C#,Sql Server,Entity Framework,Ado.net,Dbcontext,我编写了一个函数,使用模式名和表名作为输入参数,检查表中是否存在特定ID 若我创建的要在数据库上执行的查询找不到具有给定ID的记录,它将返回-2,若找到项,则返回其ID private long isThisNodeAlreadyInsertedInDatabaseByHeadquarter( string schemaName string tableName, string primaryNodeId, string primaryKeyFieldName){
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,但在Database.SqlQuery中将Int32转换为Int64会导致此异常。
我想知道这种情况是否有解决办法,或者我只需要使用SqlDataReader.ExecuteReader读取值?在查询中将PK转换为BIGINT并读取为Int64:
此外,还可以用ISNULL函数替换COALESCE:
"select CONVERT(BIGINT,ISNULL(MAX({primaryKeyFieldName}),-2))"
从方法的标题来看,我会认为如果存在的话会更快。
"select CONVERT(BIGINT,ISNULL(MAX({primaryKeyFieldName}),-2))"