我已经编写了一个函数,用表名和表名作为输入参数来检查表中是否存在特定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
相当于
Int32
和
Int64
分别为C#(或
int
和
long
分别)。
当我读取BigInt类型表的主键时,不会发生任何错误,但当我要读取Int类型表的主键时,会导致异常:
{“指定的从物化的”System.Int32“类型转换为
“System.Int64”类型无效。“}
尽管可以将int存储在长变量中,但是
国际32
到
国际64
在里面
Database.SqlQuery
导致此异常。
我想知道在这种情况下是否有解决方法,或者我只需要使用
SqlDataReader.ExecuteReader
?