DbDataAdapter.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  1. //
  2. // System.Data.Common.DbDataAdapter.cs
  3. //
  4. // Author:
  5. // Rodrigo Moya ([email protected])
  6. // Tim Coleman ([email protected])
  7. // Sureshkumar T <[email protected]>
  8. // Veerapuram Varadhan <[email protected]>
  9. //
  10. // (C) Ximian, Inc
  11. // Copyright (C) Tim Coleman, 2002-2003
  12. //
  13. //
  14. // Copyright (C) 2004, 2009 Novell, Inc (http://www.novell.com)
  15. //
  16. // Permission is hereby granted, free of charge, to any person obtaining
  17. // a copy of this software and associated documentation files (the
  18. // "Software"), to deal in the Software without restriction, including
  19. // without limitation the rights to use, copy, modify, merge, publish,
  20. // distribute, sublicense, and/or sell copies of the Software, and to
  21. // permit persons to whom the Software is furnished to do so, subject to
  22. // the following conditions:
  23. //
  24. // The above copyright notice and this permission notice shall be
  25. // included in all copies or substantial portions of the Software.
  26. //
  27. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  28. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  29. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  30. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  31. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  32. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  33. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  34. //
  35. using System;
  36. using System.Collections;
  37. using System.ComponentModel;
  38. using System.Data;
  39. using System.Reflection;
  40. using System.Runtime.InteropServices;
  41. namespace System.Data.Common
  42. {
  43. public abstract class DbDataAdapter : DataAdapter, IDbDataAdapter, IDataAdapter, ICloneable
  44. {
  45. #region Fields
  46. public const string DefaultSourceTableName = "Table";
  47. const string DefaultSourceColumnName = "Column";
  48. CommandBehavior _behavior = CommandBehavior.Default;
  49. IDbCommand _selectCommand;
  50. IDbCommand _updateCommand;
  51. IDbCommand _deleteCommand;
  52. IDbCommand _insertCommand;
  53. #endregion // Fields
  54. #region Constructors
  55. protected DbDataAdapter ()
  56. {
  57. }
  58. protected DbDataAdapter (DbDataAdapter adapter) : base (adapter)
  59. {
  60. }
  61. #endregion // Fields
  62. #region Properties
  63. protected internal CommandBehavior FillCommandBehavior {
  64. get { return _behavior; }
  65. set { _behavior = value; }
  66. }
  67. IDbCommand IDbDataAdapter.SelectCommand {
  68. get { return ((DbDataAdapter)this).SelectCommand; }
  69. set { ((DbDataAdapter)this).SelectCommand = (DbCommand)value; }
  70. }
  71. IDbCommand IDbDataAdapter.UpdateCommand{
  72. get { return ((DbDataAdapter)this).UpdateCommand; }
  73. set { ((DbDataAdapter)this).UpdateCommand = (DbCommand)value; }
  74. }
  75. IDbCommand IDbDataAdapter.DeleteCommand{
  76. get { return ((DbDataAdapter)this).DeleteCommand; }
  77. set { ((DbDataAdapter)this).DeleteCommand = (DbCommand)value; }
  78. }
  79. IDbCommand IDbDataAdapter.InsertCommand{
  80. get { return ((DbDataAdapter)this).InsertCommand; }
  81. set { ((DbDataAdapter)this).InsertCommand = (DbCommand)value; }
  82. }
  83. [Browsable (false)]
  84. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  85. public DbCommand SelectCommand {
  86. get {
  87. return (DbCommand) _selectCommand;
  88. //return (DbCommand) ((IDbDataAdapter)this).SelectCommand;
  89. }
  90. set {
  91. if (_selectCommand != value) {
  92. _selectCommand = value;
  93. ((IDbDataAdapter)this).SelectCommand = value;
  94. }
  95. }
  96. }
  97. [Browsable (false)]
  98. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  99. public DbCommand DeleteCommand {
  100. get {
  101. return (DbCommand) _deleteCommand;
  102. //return (DbCommand) ((IDbDataAdapter)this).DeleteCommand;
  103. }
  104. set {
  105. if (_deleteCommand != value) {
  106. _deleteCommand = value;
  107. ((IDbDataAdapter)this).DeleteCommand = value;
  108. }
  109. }
  110. }
  111. [Browsable (false)]
  112. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  113. public DbCommand InsertCommand {
  114. get {
  115. return (DbCommand) _insertCommand;
  116. //return (DbCommand) ((IDbDataAdapter)this).InsertCommand;
  117. }
  118. set {
  119. if (_insertCommand != value) {
  120. _insertCommand = value;
  121. ((IDbDataAdapter)this).InsertCommand = value;
  122. }
  123. }
  124. }
  125. [Browsable (false)]
  126. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  127. public DbCommand UpdateCommand {
  128. get {
  129. return (DbCommand) _updateCommand;
  130. //return (DbCommand) ((IDbDataAdapter)this).DeleteCommand;
  131. }
  132. set {
  133. if (_updateCommand != value) {
  134. _updateCommand = value;
  135. ((IDbDataAdapter)this).UpdateCommand = value;
  136. }
  137. }
  138. }
  139. [DefaultValue (1)]
  140. public virtual int UpdateBatchSize {
  141. get { return 1; }
  142. set {
  143. if (value != 1)
  144. throw new NotSupportedException ();
  145. }
  146. }
  147. #endregion // Properties
  148. #region Events
  149. #if ONLY_1_0 || ONLY_1_1
  150. [DataCategory ("Fill")]
  151. [DataSysDescription ("Event triggered when a recoverable error occurs during Fill.")]
  152. public event FillErrorEventHandler FillError;
  153. #endif
  154. #endregion // Events
  155. #region Methods
  156. protected virtual RowUpdatedEventArgs CreateRowUpdatedEvent (DataRow dataRow, IDbCommand command,
  157. StatementType statementType,
  158. DataTableMapping tableMapping)
  159. {
  160. return new RowUpdatedEventArgs (dataRow, command, statementType, tableMapping);
  161. }
  162. protected virtual RowUpdatingEventArgs CreateRowUpdatingEvent (DataRow dataRow, IDbCommand command,
  163. StatementType statementType,
  164. DataTableMapping tableMapping)
  165. {
  166. return new RowUpdatingEventArgs (dataRow, command, statementType, tableMapping);
  167. }
  168. protected virtual void OnRowUpdated (RowUpdatedEventArgs value)
  169. {
  170. if (Events ["RowUpdated"] != null) {
  171. Delegate [] rowUpdatedList = Events ["RowUpdated"].GetInvocationList ();
  172. foreach (Delegate rowUpdated in rowUpdatedList) {
  173. MethodInfo rowUpdatedMethod = rowUpdated.Method;
  174. rowUpdatedMethod.Invoke (value, null);
  175. }
  176. }
  177. }
  178. protected virtual void OnRowUpdating (RowUpdatingEventArgs value)
  179. {
  180. if (Events ["RowUpdating"] != null) {
  181. Delegate [] rowUpdatingList = Events ["RowUpdating"].GetInvocationList ();
  182. foreach (Delegate rowUpdating in rowUpdatingList) {
  183. MethodInfo rowUpdatingMethod = rowUpdating.Method;
  184. rowUpdatingMethod.Invoke (value, null);
  185. }
  186. }
  187. }
  188. protected override void Dispose (bool disposing)
  189. {
  190. if (disposing) {
  191. IDbDataAdapter da = (IDbDataAdapter) this;
  192. if (da.SelectCommand != null) {
  193. da.SelectCommand.Dispose();
  194. da.SelectCommand = null;
  195. }
  196. if (da.InsertCommand != null) {
  197. da.InsertCommand.Dispose();
  198. da.InsertCommand = null;
  199. }
  200. if (da.UpdateCommand != null) {
  201. da.UpdateCommand.Dispose();
  202. da.UpdateCommand = null;
  203. }
  204. if (da.DeleteCommand != null) {
  205. da.DeleteCommand.Dispose();
  206. da.DeleteCommand = null;
  207. }
  208. }
  209. }
  210. public override int Fill (DataSet dataSet)
  211. {
  212. return Fill (dataSet, 0, 0, DefaultSourceTableName, ((IDbDataAdapter) this).SelectCommand, _behavior);
  213. }
  214. public int Fill (DataTable dataTable)
  215. {
  216. if (dataTable == null)
  217. throw new ArgumentNullException ("DataTable");
  218. return Fill (dataTable, ((IDbDataAdapter) this).SelectCommand, _behavior);
  219. }
  220. public int Fill (DataSet dataSet, string srcTable)
  221. {
  222. return Fill (dataSet, 0, 0, srcTable, ((IDbDataAdapter) this).SelectCommand, _behavior);
  223. }
  224. protected virtual int Fill (DataTable dataTable, IDbCommand command, CommandBehavior behavior)
  225. {
  226. CommandBehavior commandBehavior = behavior;
  227. // first see that the connection is not close.
  228. if (command.Connection.State == ConnectionState.Closed) {
  229. command.Connection.Open ();
  230. commandBehavior |= CommandBehavior.CloseConnection;
  231. }
  232. return Fill (dataTable, command.ExecuteReader (commandBehavior));
  233. }
  234. public int Fill (DataSet dataSet, int startRecord, int maxRecords, string srcTable)
  235. {
  236. return this.Fill (dataSet, startRecord, maxRecords, srcTable, ((IDbDataAdapter) this).SelectCommand, _behavior);
  237. }
  238. [MonoTODO]
  239. public int Fill (int startRecord, int maxRecords, params DataTable[] dataTables)
  240. {
  241. throw new NotImplementedException ();
  242. }
  243. [MonoTODO]
  244. protected virtual int Fill (DataTable[] dataTables, int startRecord, int maxRecords, IDbCommand command, CommandBehavior behavior)
  245. {
  246. throw new NotImplementedException ();
  247. }
  248. protected virtual int Fill (DataSet dataSet, int startRecord, int maxRecords, string srcTable, IDbCommand command, CommandBehavior behavior)
  249. {
  250. if (command.Connection == null)
  251. throw new InvalidOperationException ("Connection state is closed");
  252. if (MissingSchemaAction == MissingSchemaAction.AddWithKey)
  253. behavior |= CommandBehavior.KeyInfo;
  254. CommandBehavior commandBehavior = behavior;
  255. if (command.Connection.State == ConnectionState.Closed) {
  256. command.Connection.Open ();
  257. commandBehavior |= CommandBehavior.CloseConnection;
  258. }
  259. return Fill (dataSet, srcTable, command.ExecuteReader (commandBehavior),
  260. startRecord, maxRecords);
  261. }
  262. /// <summary>
  263. /// Fills the given datatable using values from reader. if a value
  264. /// for a column is null, that will be filled with default value.
  265. /// </summary>
  266. /// <returns>No. of rows affected </returns>
  267. internal static int FillFromReader (DataTable table,
  268. IDataReader reader,
  269. int start,
  270. int length,
  271. int [] mapping,
  272. LoadOption loadOption
  273. )
  274. {
  275. if (reader.FieldCount == 0)
  276. return 0 ;
  277. for (int i = 0; i < start; i++)
  278. reader.Read ();
  279. int counter = 0;
  280. object [] values = new object [mapping.Length];
  281. while (reader.Read () && (length == 0 || counter < length)) {
  282. for (int i = 0 ; i < mapping.Length; i++)
  283. values [i] = mapping [i] < 0 ? null : reader [mapping [i]];
  284. table.BeginLoadData ();
  285. table.LoadDataRow (values, loadOption);
  286. table.EndLoadData ();
  287. counter++;
  288. }
  289. return counter;
  290. }
  291. internal static int FillFromReader (DataTable table,
  292. IDataReader reader,
  293. int start,
  294. int length,
  295. int [] mapping,
  296. LoadOption loadOption,
  297. FillErrorEventHandler errorHandler)
  298. {
  299. if (reader.FieldCount == 0)
  300. return 0 ;
  301. for (int i = 0; i < start; i++)
  302. reader.Read ();
  303. int counter = 0;
  304. object [] values = new object [mapping.Length];
  305. while (reader.Read () && (length == 0 || counter < length)) {
  306. for (int i = 0 ; i < mapping.Length; i++)
  307. values [i] = mapping [i] < 0 ? null : reader [mapping [i]];
  308. table.BeginLoadData ();
  309. try {
  310. table.LoadDataRow (values, loadOption);
  311. } catch (Exception e) {
  312. FillErrorEventArgs args = new FillErrorEventArgs (table, values);
  313. args.Errors = e;
  314. args.Continue = false;
  315. errorHandler (table, args);
  316. // if args.Continue is not set to true or if a handler is not set, rethrow the error..
  317. if(!args.Continue)
  318. throw e;
  319. }
  320. table.EndLoadData ();
  321. counter++;
  322. }
  323. return counter;
  324. }
  325. public override DataTable [] FillSchema (DataSet dataSet, SchemaType schemaType)
  326. {
  327. return FillSchema (dataSet, schemaType, ((IDbDataAdapter) this).SelectCommand, DefaultSourceTableName, _behavior);
  328. }
  329. public DataTable FillSchema (DataTable dataTable, SchemaType schemaType)
  330. {
  331. return FillSchema (dataTable, schemaType, ((IDbDataAdapter) this).SelectCommand, _behavior);
  332. }
  333. public DataTable [] FillSchema (DataSet dataSet, SchemaType schemaType, string srcTable)
  334. {
  335. return FillSchema (dataSet, schemaType, ((IDbDataAdapter) this).SelectCommand, srcTable, _behavior);
  336. }
  337. protected virtual DataTable FillSchema (DataTable dataTable, SchemaType schemaType, IDbCommand command, CommandBehavior behavior)
  338. {
  339. if (dataTable == null)
  340. throw new ArgumentNullException ("DataTable");
  341. behavior |= CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo;
  342. if (command.Connection.State == ConnectionState.Closed) {
  343. command.Connection.Open ();
  344. behavior |= CommandBehavior.CloseConnection;
  345. }
  346. IDataReader reader = command.ExecuteReader (behavior);
  347. try {
  348. string tableName = SetupSchema (schemaType, dataTable.TableName);
  349. if (tableName != null) {
  350. // FillSchema should add the KeyInfo unless MissingSchemaAction
  351. // is set to Ignore or Error.
  352. MissingSchemaAction schemaAction = MissingSchemaAction;
  353. if (!(schemaAction == MissingSchemaAction.Ignore ||
  354. schemaAction == MissingSchemaAction.Error))
  355. schemaAction = MissingSchemaAction.AddWithKey;
  356. BuildSchema (reader, dataTable, schemaType, schemaAction,
  357. MissingMappingAction, TableMappings);
  358. }
  359. } finally {
  360. reader.Close ();
  361. }
  362. return dataTable;
  363. }
  364. protected virtual DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType, IDbCommand command, string srcTable, CommandBehavior behavior)
  365. {
  366. if (dataSet == null)
  367. throw new ArgumentNullException ("DataSet");
  368. behavior |= CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo;
  369. if (command.Connection.State == ConnectionState.Closed) {
  370. command.Connection.Open ();
  371. behavior |= CommandBehavior.CloseConnection;
  372. }
  373. IDataReader reader = command.ExecuteReader (behavior);
  374. ArrayList output = new ArrayList ();
  375. string tableName = srcTable;
  376. int index = 0;
  377. DataTable table;
  378. try {
  379. // FillSchema should add the KeyInfo unless MissingSchemaAction
  380. // is set to Ignore or Error.
  381. MissingSchemaAction schemaAction = MissingSchemaAction;
  382. if (!(MissingSchemaAction == MissingSchemaAction.Ignore ||
  383. MissingSchemaAction == MissingSchemaAction.Error))
  384. schemaAction = MissingSchemaAction.AddWithKey;
  385. do {
  386. tableName = SetupSchema (schemaType, tableName);
  387. if (tableName != null) {
  388. if (dataSet.Tables.Contains (tableName))
  389. table = dataSet.Tables [tableName];
  390. else {
  391. // Do not create schema if MissingSchemAction is set to Ignore
  392. if (this.MissingSchemaAction == MissingSchemaAction.Ignore)
  393. continue;
  394. table = dataSet.Tables.Add (tableName);
  395. }
  396. BuildSchema (reader, table, schemaType, schemaAction,
  397. MissingMappingAction, TableMappings);
  398. output.Add (table);
  399. tableName = String.Format ("{0}{1}", srcTable, ++index);
  400. }
  401. }while (reader.NextResult ());
  402. } finally {
  403. reader.Close ();
  404. }
  405. return (DataTable []) output.ToArray (typeof (DataTable));
  406. }
  407. [EditorBrowsable (EditorBrowsableState.Advanced)]
  408. public override IDataParameter[] GetFillParameters ()
  409. {
  410. IDbCommand selectCmd = ((IDbDataAdapter) this).SelectCommand;
  411. IDataParameter[] parameters = new IDataParameter [selectCmd.Parameters.Count];
  412. selectCmd.Parameters.CopyTo (parameters, 0);
  413. return parameters;
  414. }
  415. [MonoTODO]
  416. [Obsolete ("use 'protected DbDataAdapter(DbDataAdapter)' ctor")]
  417. object ICloneable.Clone ()
  418. {
  419. throw new NotImplementedException ();
  420. }
  421. public int Update (DataRow [] dataRows)
  422. {
  423. if (dataRows == null)
  424. throw new ArgumentNullException("dataRows");
  425. if (dataRows.Length == 0)
  426. return 0;
  427. if (dataRows [0] == null)
  428. throw new ArgumentException("dataRows[0].");
  429. DataTable table = dataRows [0].Table;
  430. if (table == null)
  431. throw new ArgumentException("table is null reference.");
  432. // all rows must be in the same table
  433. for (int i = 0; i < dataRows.Length; i++) {
  434. if (dataRows [i] == null)
  435. throw new ArgumentException ("dataRows[" + i + "].");
  436. if (dataRows [i].Table != table)
  437. throw new ArgumentException(
  438. " DataRow["
  439. + i
  440. + "] is from a different DataTable than DataRow[0].");
  441. }
  442. // get table mapping for this rows
  443. DataTableMapping tableMapping = TableMappings.GetByDataSetTable(table.TableName);
  444. if (tableMapping == null) {
  445. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction(
  446. TableMappings,
  447. table.TableName,
  448. table.TableName,
  449. MissingMappingAction);
  450. if (tableMapping != null) {
  451. foreach (DataColumn col in table.Columns) {
  452. if (tableMapping.ColumnMappings.IndexOf (col.ColumnName) >= 0)
  453. continue;
  454. DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction (tableMapping.ColumnMappings, col.ColumnName, MissingMappingAction);
  455. if (columnMapping == null)
  456. columnMapping = new DataColumnMapping (col.ColumnName, col.ColumnName);
  457. tableMapping.ColumnMappings.Add (columnMapping);
  458. }
  459. } else {
  460. ArrayList cmc = new ArrayList ();
  461. foreach (DataColumn col in table.Columns)
  462. cmc.Add (new DataColumnMapping (col.ColumnName, col.ColumnName));
  463. tableMapping =
  464. new DataTableMapping (
  465. table.TableName,
  466. table.TableName,
  467. cmc.ToArray (typeof (DataColumnMapping)) as DataColumnMapping []);
  468. }
  469. }
  470. DataRow[] copy = table.NewRowArray (dataRows.Length);
  471. Array.Copy (dataRows, 0, copy, 0, dataRows.Length);
  472. return Update (copy, tableMapping);
  473. }
  474. public override int Update (DataSet dataSet)
  475. {
  476. return Update (dataSet, DefaultSourceTableName);
  477. }
  478. public int Update (DataTable dataTable)
  479. {
  480. /*
  481. int index = TableMappings.IndexOfDataSetTable (dataTable.TableName);
  482. if (index < 0)
  483. throw new ArgumentException ();
  484. return Update (dataTable, TableMappings [index]);
  485. */
  486. DataTableMapping tableMapping = TableMappings.GetByDataSetTable (dataTable.TableName);
  487. if (tableMapping == null) {
  488. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (
  489. TableMappings,
  490. dataTable.TableName,
  491. dataTable.TableName,
  492. MissingMappingAction);
  493. if (tableMapping != null) {
  494. foreach (DataColumn col in dataTable.Columns) {
  495. if (tableMapping.ColumnMappings.IndexOf (col.ColumnName) >= 0)
  496. continue;
  497. DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction (tableMapping.ColumnMappings, col.ColumnName, MissingMappingAction);
  498. if (columnMapping == null)
  499. columnMapping = new DataColumnMapping (col.ColumnName, col.ColumnName);
  500. tableMapping.ColumnMappings.Add (columnMapping);
  501. }
  502. } else {
  503. ArrayList cmc = new ArrayList ();
  504. foreach (DataColumn col in dataTable.Columns)
  505. cmc.Add (new DataColumnMapping (col.ColumnName, col.ColumnName));
  506. tableMapping =
  507. new DataTableMapping (
  508. dataTable.TableName,
  509. dataTable.TableName,
  510. cmc.ToArray (typeof (DataColumnMapping)) as DataColumnMapping []);
  511. }
  512. }
  513. return Update (dataTable, tableMapping);
  514. }
  515. private int Update (DataTable dataTable, DataTableMapping tableMapping)
  516. {
  517. DataRow [] rows = dataTable.NewRowArray(dataTable.Rows.Count);
  518. dataTable.Rows.CopyTo (rows, 0);
  519. return Update (rows, tableMapping);
  520. }
  521. protected virtual int Update (DataRow [] dataRows, DataTableMapping tableMapping)
  522. {
  523. int updateCount = 0;
  524. foreach (DataRow row in dataRows) {
  525. StatementType statementType = StatementType.Update;
  526. IDbCommand command = null;
  527. string commandName = String.Empty;
  528. switch (row.RowState) {
  529. case DataRowState.Added:
  530. statementType = StatementType.Insert;
  531. command = ((IDbDataAdapter) this).InsertCommand;
  532. commandName = "Insert";
  533. break;
  534. case DataRowState.Deleted:
  535. statementType = StatementType.Delete;
  536. command = ((IDbDataAdapter) this).DeleteCommand;
  537. commandName = "Delete";
  538. break;
  539. case DataRowState.Modified:
  540. statementType = StatementType.Update;
  541. command = ((IDbDataAdapter) this).UpdateCommand;
  542. commandName = "Update";
  543. break;
  544. case DataRowState.Unchanged:
  545. case DataRowState.Detached:
  546. continue;
  547. }
  548. RowUpdatingEventArgs argsUpdating = CreateRowUpdatingEvent (row, command, statementType, tableMapping);
  549. row.RowError = String.Empty;
  550. OnRowUpdating (argsUpdating);
  551. switch (argsUpdating.Status) {
  552. case UpdateStatus.Continue :
  553. //continue in update operation
  554. break;
  555. case UpdateStatus.ErrorsOccurred :
  556. if (argsUpdating.Errors == null)
  557. argsUpdating.Errors = ExceptionHelper.RowUpdatedError();
  558. row.RowError += argsUpdating.Errors.Message;
  559. if (!ContinueUpdateOnError)
  560. throw argsUpdating.Errors;
  561. continue;
  562. case UpdateStatus.SkipAllRemainingRows :
  563. return updateCount;
  564. case UpdateStatus.SkipCurrentRow :
  565. updateCount++;
  566. continue;
  567. default :
  568. throw ExceptionHelper.InvalidUpdateStatus (argsUpdating.Status);
  569. }
  570. command = argsUpdating.Command;
  571. try {
  572. if (command != null) {
  573. DataColumnMappingCollection columnMappings = tableMapping.ColumnMappings;
  574. foreach (IDataParameter parameter in command.Parameters) {
  575. if ((parameter.Direction & ParameterDirection.Input) == 0)
  576. continue;
  577. DataRowVersion rowVersion = parameter.SourceVersion;
  578. // Parameter version is ignored for non-update commands
  579. if (statementType == StatementType.Delete)
  580. rowVersion = DataRowVersion.Original;
  581. string dsColumnName = parameter.SourceColumn;
  582. if (columnMappings.Contains(dsColumnName)) {
  583. dsColumnName = columnMappings [dsColumnName].DataSetColumn;
  584. parameter.Value = row [dsColumnName, rowVersion];
  585. } else {
  586. parameter.Value = null;
  587. }
  588. DbParameter nullCheckParam = parameter as DbParameter;
  589. if (nullCheckParam != null && nullCheckParam.SourceColumnNullMapping) {
  590. if (parameter.Value != null && parameter.Value != DBNull.Value)
  591. nullCheckParam.Value = 0;
  592. else
  593. nullCheckParam.Value = 1;
  594. nullCheckParam = null;
  595. }
  596. }
  597. }
  598. } catch (Exception e) {
  599. argsUpdating.Errors = e;
  600. argsUpdating.Status = UpdateStatus.ErrorsOccurred;
  601. }
  602. IDataReader reader = null;
  603. try {
  604. if (command == null)
  605. throw ExceptionHelper.UpdateRequiresCommand (commandName);
  606. CommandBehavior commandBehavior = CommandBehavior.Default;
  607. if (command.Connection.State == ConnectionState.Closed) {
  608. command.Connection.Open ();
  609. commandBehavior |= CommandBehavior.CloseConnection;
  610. }
  611. // use ExecuteReader because we want to use the commandbehavior parameter.
  612. // so the connection will be closed if needed.
  613. reader = command.ExecuteReader (commandBehavior);
  614. // update the current row, if the update command returns any resultset
  615. // ignore other than the first record.
  616. DataColumnMappingCollection columnMappings = tableMapping.ColumnMappings;
  617. if (command.UpdatedRowSource == UpdateRowSource.Both ||
  618. command.UpdatedRowSource == UpdateRowSource.FirstReturnedRecord) {
  619. if (reader.Read ()){
  620. DataTable retSchema = reader.GetSchemaTable ();
  621. foreach (DataRow dr in retSchema.Rows) {
  622. string columnName = dr ["ColumnName"].ToString ();
  623. string dstColumnName = columnName;
  624. if (columnMappings != null &&
  625. columnMappings.Contains(columnName))
  626. dstColumnName = columnMappings [dstColumnName].DataSetColumn;
  627. DataColumn dstColumn = row.Table.Columns [dstColumnName];
  628. if (dstColumn == null
  629. || (dstColumn.Expression != null
  630. && dstColumn.Expression.Length > 0))
  631. continue;
  632. // info from : http://www.error-bank.com/microsoft.public.dotnet.framework.windowsforms.databinding/
  633. // [email protected]_Thread.aspx
  634. // disable readonly for non-expression columns.
  635. bool readOnlyState = dstColumn.ReadOnly;
  636. dstColumn.ReadOnly = false;
  637. try {
  638. row [dstColumnName] = reader [columnName];
  639. } finally {
  640. dstColumn.ReadOnly = readOnlyState;
  641. }
  642. }
  643. }
  644. }
  645. reader.Close ();
  646. int tmp = reader.RecordsAffected; // records affected is valid only after closing reader
  647. // if the execute does not effect any rows we throw an exception.
  648. if (tmp == 0)
  649. throw new DBConcurrencyException("Concurrency violation: the " +
  650. commandName +"Command affected 0 records.", null,
  651. new DataRow [] { row });
  652. updateCount += tmp;
  653. if (command.UpdatedRowSource == UpdateRowSource.Both ||
  654. command.UpdatedRowSource == UpdateRowSource.OutputParameters) {
  655. // Update output parameters to row values
  656. foreach (IDataParameter parameter in command.Parameters) {
  657. if (parameter.Direction != ParameterDirection.InputOutput
  658. && parameter.Direction != ParameterDirection.Output
  659. && parameter.Direction != ParameterDirection.ReturnValue)
  660. continue;
  661. string dsColumnName = parameter.SourceColumn;
  662. if (columnMappings != null &&
  663. columnMappings.Contains(parameter.SourceColumn))
  664. dsColumnName = columnMappings [parameter.SourceColumn].DataSetColumn;
  665. DataColumn dstColumn = row.Table.Columns [dsColumnName];
  666. if (dstColumn == null
  667. || (dstColumn.Expression != null
  668. && dstColumn.Expression.Length > 0))
  669. continue;
  670. bool readOnlyState = dstColumn.ReadOnly;
  671. dstColumn.ReadOnly = false;
  672. try {
  673. row [dsColumnName] = parameter.Value;
  674. } finally {
  675. dstColumn.ReadOnly = readOnlyState;
  676. }
  677. }
  678. }
  679. RowUpdatedEventArgs updatedArgs = CreateRowUpdatedEvent (row, command, statementType, tableMapping);
  680. OnRowUpdated (updatedArgs);
  681. switch (updatedArgs.Status) {
  682. case UpdateStatus.Continue:
  683. break;
  684. case UpdateStatus.ErrorsOccurred:
  685. if (updatedArgs.Errors == null)
  686. updatedArgs.Errors = ExceptionHelper.RowUpdatedError();
  687. row.RowError += updatedArgs.Errors.Message;
  688. if (!ContinueUpdateOnError)
  689. throw updatedArgs.Errors;
  690. break;
  691. case UpdateStatus.SkipCurrentRow:
  692. continue;
  693. case UpdateStatus.SkipAllRemainingRows:
  694. return updateCount;
  695. }
  696. if (!AcceptChangesDuringUpdate)
  697. continue;
  698. row.AcceptChanges ();
  699. } catch (Exception e) {
  700. row.RowError = e.Message;
  701. if (!ContinueUpdateOnError)
  702. throw e;
  703. } finally {
  704. if (reader != null && ! reader.IsClosed)
  705. reader.Close ();
  706. }
  707. }
  708. return updateCount;
  709. }
  710. public int Update (DataSet dataSet, string srcTable)
  711. {
  712. MissingMappingAction mappingAction = MissingMappingAction;
  713. if (mappingAction == MissingMappingAction.Ignore)
  714. mappingAction = MissingMappingAction.Error;
  715. DataTableMapping tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, srcTable, srcTable, mappingAction);
  716. DataTable dataTable = dataSet.Tables [tableMapping.DataSetTable];
  717. if (dataTable == null)
  718. throw new ArgumentException (String.Format ("Missing table {0}",
  719. srcTable));
  720. /** Copied from another Update function **/
  721. if (tableMapping != null) {
  722. foreach (DataColumn col in dataTable.Columns) {
  723. if (tableMapping.ColumnMappings.IndexOf (col.ColumnName) >= 0)
  724. continue;
  725. DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction (tableMapping.ColumnMappings, col.ColumnName, MissingMappingAction);
  726. if (columnMapping == null)
  727. columnMapping = new DataColumnMapping (col.ColumnName, col.ColumnName);
  728. tableMapping.ColumnMappings.Add (columnMapping);
  729. }
  730. } else {
  731. ArrayList cmc = new ArrayList ();
  732. foreach (DataColumn col in dataTable.Columns)
  733. cmc.Add (new DataColumnMapping (col.ColumnName, col.ColumnName));
  734. tableMapping =
  735. new DataTableMapping (
  736. dataTable.TableName,
  737. dataTable.TableName,
  738. cmc.ToArray (typeof (DataColumnMapping)) as DataColumnMapping []);
  739. }
  740. /**end insert from another update**/
  741. return Update (dataTable, tableMapping);
  742. }
  743. // All the batch methods, should be implemented, if supported,
  744. // by individual providers
  745. protected virtual int AddToBatch (IDbCommand command)
  746. {
  747. throw CreateMethodNotSupportedException ();
  748. }
  749. protected virtual void ClearBatch ()
  750. {
  751. throw CreateMethodNotSupportedException ();
  752. }
  753. protected virtual int ExecuteBatch ()
  754. {
  755. throw CreateMethodNotSupportedException ();
  756. }
  757. protected virtual IDataParameter GetBatchedParameter (int commandIdentifier, int parameterIndex)
  758. {
  759. throw CreateMethodNotSupportedException ();
  760. }
  761. protected virtual bool GetBatchedRecordsAffected (int commandIdentifier, out int recordsAffected, out Exception error)
  762. {
  763. recordsAffected = 1;
  764. error = null;
  765. return true;
  766. }
  767. protected virtual void InitializeBatching ()
  768. {
  769. throw CreateMethodNotSupportedException ();
  770. }
  771. protected virtual void TerminateBatching ()
  772. {
  773. throw CreateMethodNotSupportedException ();
  774. }
  775. Exception CreateMethodNotSupportedException ()
  776. {
  777. return new NotSupportedException ("Method is not supported.");
  778. }
  779. #endregion // Methods
  780. }
  781. }