rendered paste body/// <summary>
/// Atualiza as alterações nas tabelas no banco de dados.
/// </summary>
/// <param name="tables">As tabelas que devem ser atualizadas</param>
/// <returns>O número de linhas modificadas</returns>
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())
{
DataTable add = dt.GetChanges(DataRowState.Added);
DataTable del = dt.GetChanges(DataRowState.Deleted);
DataTable upd = dt.GetChanges(DataRowState.Modified);
if (add != null || del != null || upd != null)
if (!BuildCommands(da, conn, dt))
new AdpCommandBuilder(da, conn, dt);
if (del != null)
{
modCount += da.Update(del);
ds.Merge(del);
}
if (upd != null)
{
modCount += da.Update(upd);
ds.Merge(upd);
}
if (add != null)
{
AdpCommand autoIncrementCmd = null;
if (conn.Provider is MsSqlProvider)
{
autoIncrementCmd = conn.CreateCommand();
autoIncrementCmd.CommandText = "SELECT @@IDENTITY";
}
else
Debug.WriteLine("Provider not supported: " + conn.Provider);
if (autoIncrementCmd == null)
modCount += da.Update(add);
else
{
autoIncrementCmd.Prepare();
foreach (DataRow row in add.Rows)
{
da.Update(row);
if (add.PrimaryKey.Length == 1 && add.PrimaryKey[0].AutoIncrement)
{
DataColumn pk = add.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);
}
}