public bool Save(IAdfQuery query, IInternalState data)
{
var result = false;
if (query == null || data == null) return false;
if (!data.IsAltered) return true;
var rowState = data as RowState;
if (rowState == null) return false;
var row = rowState.BuildUpDataRow();
if (row == null) return false;
IDbConnection connection = Provider.GetConnection(DataSource);
IDbDataAdapter da = Provider.SetUpAdapter(DataSource, connection, query);
try
{
if (connection.State == ConnectionState.Closed) connection.Open();
IDbTransaction transaction = Provider.GetTransaction(DataSource);
if (transaction != null) da.SelectCommand.Transaction = transaction;
var autoincrement = row.Table.Columns.Cast<DataColumn>().FirstOrDefault(column => column.AutoIncrement);
if (autoincrement != null)
{
da.InsertCommand.CommandText += "; if (IsNumeric(SCOPE_IDENTITY()) = 1) select SCOPE_IDENTITY() as " + autoincrement.ColumnName;
}
var count = Provider.Update(da, row);
// The count should never be more than 1, since we request to update only 1 record. If the count is more than 1,
// it means that the Provider updates the DataSet instead of the DataRow.
if (count != 1) throw new DataException(string.Format("Saving {0} ({1}) changed {2} rows", query.LeadTable(), rowState.ID, count));
rowState.AcceptChanges();
result = true;
}
catch (Exception exception)
{
Provider.HandleException(exception, DataSource, query);
}
finally
{
if (da.SelectCommand.Transaction == null) connection.Close();
}
return result;
}