使用 .net core 和 Oracle.ManagedDataAccess.Core 从 Oracle 查询中获取 ID

Getting IDs back from an Oracle query using .net core and Oracle.ManagedDataAccess.Core

我有以下代码:

List<foo> collection = getData();
using (OracleConnection conn = _client.GetConnection())
{
    await conn.OpenAsync();
    using (OracleTransaction transaction = conn.BeginTransaction(IsolationLevel.ReadCommitted))
    using (OracleCommand cmd = new OracleCommand())
    {
        cmd.Transaction = transaction;
        cmd.Connection = conn;
        cmd.CommandText = @"INSERT INTO SOME.TABLE
                           (A, B, C)
                           VALUES
                           (:A, :B, :C)";
        cmd.ArrayBindCount = collection.Count;
        cmd.Parameters.Add(":A", OracleDbType.Varchar2, collection.Select(c => c.A).ToArray(), ParameterDirection.Input);
        cmd.Parameters.Add(":B", OracleDbType.Varchar2, collection.Select(c => c.B).ToArray(), ParameterDirection.Input);
        cmd.Parameters.Add(":C", OracleDbType.Varchar2, collection.Select(c => c.C).ToArray(), ParameterDirection.Input);

        try
        {
            await cmd.ExecuteNonQueryAsync();
            transaction.Commit();
        }
        catch (Exception ex)
        {
            transaction.Rollback();
            throw new FailedTransactionException(ex.ToString());
        }
    }
}

在这里,我可以从我的集合中插入多行数据,但我需要以某种方式 return 插入行的 ID。有人能给我指出正确的方向吗?或者是否有更好的方法来插入对象数组并取回 ID。

您可以通过这样做取回生成的 ID:

@"INSERT INTO SOME.TABLE
  (A, B, C)
  VALUES
  (:A, :B, :C) 
  RETURNING <YOUR-ID-FIELD> INTO :resultId";

并像这样声明结果参数:

var resultParam = new OracleParameter(":resultId", OracleDbType.Decimal /* or whatever type of your identifier has */);
resultParam.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(resultParam);

然后你可以从它的值属性执行查询后从参数中读取结果:

var result = resultParam.Value