DbDataAdapter.cs 30 KB

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