0

我有以下代码:

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());
        }
    }
}

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

4

1 回答 1

1

您可以通过执行以下操作取回生成的 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);

然后,您可以在从其 Value 属性执行查询后从参数中读取结果:

var result = resultParam.Value
于 2018-10-29T19:03:54.600 回答