2
0

DbDataAdapter.cs 29 KB

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