/// /// Atualiza as alterações nas tabelas no banco de dados. /// /// As tabelas que devem ser atualizadas /// O número de linhas modificadas protected int CommitChanges(params DataTable[] tables) { try { int modCount = 0; using (AdpConnection conn = CreateConnection()) foreach (DataTable dt in tables) { if (dt != null && dt.Rows.Count > 0) { string originalTableName = dt.TableName; dt.TableName = GetPhysicalTableName(originalTableName); using (AdpDataAdapter da = new AdpDataAdapter()) { DataRow[] add = dt.Select(null, null, DataViewRowState.Added); DataRow[] del = dt.Select(null, null, DataViewRowState.Deleted); DataRow[] upd = dt.Select(null, null, DataViewRowState.ModifiedCurrent); if (add.Length > 0 || del.Length > 0 || upd.Length > 0) if (!BuildCommands(da, conn, dt)) new AdpCommandBuilder(da, conn, dt); if (del.Length > 0) { modCount += da.Update(del); ds.Merge(del); } if (upd.Length > 0) { modCount += da.Update(upd); ds.Merge(upd); } if (add.Length > 0) { AdpCommand autoIncrementCmd = null; if (conn.Provider is MsSqlProvider) { autoIncrementCmd = conn.CreateCommand(); autoIncrementCmd.CommandText = "SELECT IDENT_CURRENT('" + dt.TableName + "')"; } else Debug.WriteLine("Provider not supported: " + conn.Provider); if (autoIncrementCmd == null) modCount += da.Update(add); else { // autoIncrementCmd.Prepare(); foreach (DataRow row in add) { da.Update(row); if (dt.PrimaryKey.Length == 1 && dt.PrimaryKey[0].AutoIncrement) { DataColumn pk = dt.PrimaryKey[0]; object id; id = autoIncrementCmd.ExecuteScalar(); if (!(id is DBNull)) { bool oldRO = pk.ReadOnly; pk.ReadOnly = false; row[pk] = id; pk.ReadOnly = oldRO; } } modCount++; } } ds.Merge(add); } } dt.TableName = originalTableName; } } return modCount; } catch (Exception ex) { if (ex.Message.StartsWith("DELETE statement conflicted with COLUMN REFERENCE constraint")) throw new ConnectorException(ConnectorException.Types.ForeignKeyViolation, ex); else throw new ConnectorException(ex); } }