我编写了一个函数,使用模式名和表名作为输入参数来检查表中是否存在特定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存储在长变量中,但是将Int32
转换为Int64
中的Database.SqlQuery
会导致此异常。
我想知道是否有针对这种情况的解决方法,或者我只需要使用SqlDataReader.ExecuteReader
来读取值?