我有以下代码:
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。
答案 0 :(得分:0)
您可以通过执行以下操作来获取生成的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