DbDataAdapter.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. //
  2. // System.Data.Common.DbDataAdapter.cs
  3. //
  4. // Author:
  5. // Rodrigo Moya ([email protected])
  6. // Tim Coleman ([email protected])
  7. //
  8. // (C) Ximian, Inc
  9. // Copyright (C) Tim Coleman, 2002-2003
  10. //
  11. //
  12. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  13. //
  14. // Permission is hereby granted, free of charge, to any person obtaining
  15. // a copy of this software and associated documentation files (the
  16. // "Software"), to deal in the Software without restriction, including
  17. // without limitation the rights to use, copy, modify, merge, publish,
  18. // distribute, sublicense, and/or sell copies of the Software, and to
  19. // permit persons to whom the Software is furnished to do so, subject to
  20. // the following conditions:
  21. //
  22. // The above copyright notice and this permission notice shall be
  23. // included in all copies or substantial portions of the Software.
  24. //
  25. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  28. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  29. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. //
  33. using System;
  34. using System.Collections;
  35. using System.ComponentModel;
  36. using System.Data;
  37. using System.Runtime.InteropServices;
  38. namespace System.Data.Common {
  39. public abstract class DbDataAdapter : DataAdapter, ICloneable
  40. {
  41. #region Fields
  42. public const string DefaultSourceTableName = "Table";
  43. const string DefaultSourceColumnName = "Column";
  44. #endregion // Fields
  45. #region Constructors
  46. protected DbDataAdapter()
  47. {
  48. }
  49. [MonoTODO]
  50. protected DbDataAdapter(DbDataAdapter adapter) : base(adapter)
  51. {
  52. }
  53. #endregion // Fields
  54. #region Properties
  55. #if NET_2_0
  56. [MonoTODO]
  57. protected virtual IDbConnection BaseConnection {
  58. get { throw new NotImplementedException (); }
  59. set { throw new NotImplementedException (); }
  60. }
  61. public IDbConnection Connection {
  62. get { return BaseConnection; }
  63. set { BaseConnection = value; }
  64. }
  65. #endif
  66. IDbCommand DeleteCommand {
  67. get { return ((IDbDataAdapter) this).DeleteCommand; }
  68. }
  69. #if NET_2_0
  70. protected internal CommandBehavior FillCommandBehavior {
  71. get { throw new NotImplementedException (); }
  72. set { throw new NotImplementedException (); }
  73. }
  74. #endif
  75. IDbCommand InsertCommand {
  76. get { return ((IDbDataAdapter) this).InsertCommand; }
  77. }
  78. #if NET_2_0
  79. [MonoTODO]
  80. protected virtual IDbCommand this [[Optional] StatementType statementType] {
  81. get { throw new NotImplementedException (); }
  82. set { throw new NotImplementedException (); }
  83. }
  84. protected virtual DbProviderFactory ProviderFactory {
  85. get { throw new NotImplementedException (); }
  86. }
  87. #endif
  88. IDbCommand SelectCommand {
  89. get { return ((IDbDataAdapter) this).SelectCommand; }
  90. }
  91. #if NET_2_0
  92. [MonoTODO]
  93. public IDbTransaction Transaction {
  94. get { throw new NotImplementedException (); }
  95. set { throw new NotImplementedException (); }
  96. }
  97. [MonoTODO]
  98. public int UpdateBatchSize {
  99. get { throw new NotImplementedException (); }
  100. set { throw new NotImplementedException (); }
  101. }
  102. #endif
  103. IDbCommand UpdateCommand {
  104. get { return ((IDbDataAdapter) this).UpdateCommand; }
  105. }
  106. #endregion // Properties
  107. #region Events
  108. #if ONLY_1_0 || ONLY_1_1
  109. [DataCategory ("Fill")]
  110. [DataSysDescription ("Event triggered when a recoverable error occurs during Fill.")]
  111. public event FillErrorEventHandler FillError;
  112. #endif
  113. #endregion // Events
  114. #region Methods
  115. #if NET_2_0
  116. [MonoTODO]
  117. public virtual void BeginInit ()
  118. {
  119. throw new NotImplementedException ();
  120. }
  121. #endif
  122. protected abstract RowUpdatedEventArgs CreateRowUpdatedEvent (DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping);
  123. protected abstract RowUpdatingEventArgs CreateRowUpdatingEvent (DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping);
  124. private FillErrorEventArgs CreateFillErrorEvent (DataTable dataTable, object[] values, Exception e)
  125. {
  126. FillErrorEventArgs args = new FillErrorEventArgs (dataTable, values);
  127. args.Errors = e;
  128. args.Continue = false;
  129. return args;
  130. }
  131. protected override void Dispose (bool disposing)
  132. {
  133. if (disposing) {
  134. IDbDataAdapter da = (IDbDataAdapter) this;
  135. if (da.SelectCommand != null) {
  136. da.SelectCommand.Dispose();
  137. da.SelectCommand = null;
  138. }
  139. if (da.InsertCommand != null) {
  140. da.InsertCommand.Dispose();
  141. da.InsertCommand = null;
  142. }
  143. if (da.UpdateCommand != null) {
  144. da.UpdateCommand.Dispose();
  145. da.UpdateCommand = null;
  146. }
  147. if (da.DeleteCommand != null) {
  148. da.DeleteCommand.Dispose();
  149. da.DeleteCommand = null;
  150. }
  151. }
  152. }
  153. #if NET_2_0
  154. [MonoTODO]
  155. public virtual void EndInit ()
  156. {
  157. throw new NotImplementedException ();
  158. }
  159. #endif
  160. public override int Fill (DataSet dataSet)
  161. {
  162. return Fill (dataSet, 0, 0, DefaultSourceTableName, SelectCommand, CommandBehavior.Default);
  163. }
  164. public int Fill (DataTable dataTable)
  165. {
  166. if (dataTable == null)
  167. throw new NullReferenceException ();
  168. return Fill (dataTable, SelectCommand, CommandBehavior.Default);
  169. }
  170. public int Fill (DataSet dataSet, string srcTable)
  171. {
  172. return Fill (dataSet, 0, 0, srcTable, SelectCommand, CommandBehavior.Default);
  173. }
  174. #if NET_2_0
  175. protected override int Fill (DataTable dataTable, IDataReader dataReader)
  176. #else
  177. protected virtual int Fill (DataTable dataTable, IDataReader dataReader)
  178. #endif
  179. {
  180. if (dataReader.FieldCount == 0) {
  181. dataReader.Close ();
  182. return 0;
  183. }
  184. int count = 0;
  185. try {
  186. string tableName = SetupSchema (SchemaType.Mapped, dataTable.TableName);
  187. if (tableName != null) {
  188. dataTable.TableName = tableName;
  189. FillTable (dataTable, dataReader, 0, 0, ref count);
  190. }
  191. } finally {
  192. dataReader.Close ();
  193. }
  194. return count;
  195. }
  196. protected virtual int Fill (DataTable dataTable, IDbCommand command, CommandBehavior behavior)
  197. {
  198. CommandBehavior commandBehavior = behavior;
  199. // first see that the connection is not close.
  200. if (command.Connection.State == ConnectionState.Closed)
  201. {
  202. command.Connection.Open ();
  203. commandBehavior |= CommandBehavior.CloseConnection;
  204. }
  205. return Fill (dataTable, command.ExecuteReader (commandBehavior));
  206. }
  207. #if NET_2_0
  208. [MonoTODO]
  209. public int Fill (int startRecord, int maxRecords, DataTable[] dataTables)
  210. {
  211. throw new NotImplementedException ();
  212. }
  213. #endif
  214. public int Fill (DataSet dataSet, int startRecord, int maxRecords, string srcTable)
  215. {
  216. return this.Fill (dataSet, startRecord, maxRecords, srcTable, SelectCommand, CommandBehavior.Default);
  217. }
  218. #if NET_2_0
  219. [MonoTODO]
  220. protected virtual int Fill (DataTable[] dataTables, int startRecord, int maxRecords, IDbCommand command, CommandBehavior behavior)
  221. {
  222. throw new NotImplementedException ();
  223. }
  224. #endif
  225. #if NET_2_0
  226. protected override int Fill (DataSet dataSet, string srcTable, IDataReader dataReader, int startRecord, int maxRecords)
  227. #else
  228. protected virtual int Fill (DataSet dataSet, string srcTable, IDataReader dataReader, int startRecord, int maxRecords)
  229. #endif
  230. {
  231. if (startRecord < 0)
  232. throw new ArgumentException ("The startRecord parameter was less than 0.");
  233. if (maxRecords < 0)
  234. throw new ArgumentException ("The maxRecords parameter was less than 0.");
  235. DataTable dataTable;
  236. int resultIndex = 0;
  237. int count = 0;
  238. try {
  239. string tableName = srcTable;
  240. do {
  241. tableName = SetupSchema (SchemaType.Mapped, tableName);
  242. if (tableName != null) {
  243. // check if the table exists in the dataset
  244. if (dataSet.Tables.Contains (tableName))
  245. // get the table from the dataset
  246. dataTable = dataSet.Tables [tableName];
  247. else {
  248. dataTable = new DataTable(tableName);
  249. dataSet.Tables.Add (dataTable);
  250. }
  251. if (!FillTable (dataTable, dataReader, startRecord, maxRecords, ref count)) {
  252. continue;
  253. }
  254. tableName = String.Format ("{0}{1}", srcTable, ++resultIndex);
  255. startRecord = 0;
  256. maxRecords = 0;
  257. }
  258. } while (dataReader.NextResult ());
  259. }
  260. finally {
  261. dataReader.Close ();
  262. }
  263. return count;
  264. }
  265. protected virtual int Fill (DataSet dataSet, int startRecord, int maxRecords, string srcTable, IDbCommand command, CommandBehavior behavior)
  266. {
  267. if (MissingSchemaAction == MissingSchemaAction.AddWithKey)
  268. behavior |= CommandBehavior.KeyInfo;
  269. CommandBehavior commandBehavior = behavior;
  270. if (command.Connection.State == ConnectionState.Closed) {
  271. command.Connection.Open ();
  272. commandBehavior |= CommandBehavior.CloseConnection;
  273. }
  274. return Fill (dataSet, srcTable, command.ExecuteReader (commandBehavior), startRecord, maxRecords);
  275. }
  276. private bool FillTable (DataTable dataTable, IDataReader dataReader, int startRecord, int maxRecords, ref int counter)
  277. {
  278. if (dataReader.FieldCount == 0) {
  279. return false;
  280. }
  281. int counterStart = counter;
  282. int[] mapping = BuildSchema (dataReader, dataTable, SchemaType.Mapped);
  283. for (int i = 0; i < startRecord; i++) {
  284. dataReader.Read ();
  285. }
  286. while (dataReader.Read () && (maxRecords == 0 || (counter - counterStart) < maxRecords)) {
  287. try {
  288. dataTable.BeginLoadData ();
  289. dataTable.LoadDataRow (dataReader, mapping, AcceptChangesDuringFill);
  290. dataTable.EndLoadData ();
  291. counter++;
  292. }
  293. catch (Exception e) {
  294. object[] readerArray = new object[dataReader.FieldCount];
  295. object[] tableArray = new object[mapping.Length];
  296. // we get the values from the datareader
  297. dataReader.GetValues (readerArray);
  298. // copy from datareader columns to table columns according to given mapping
  299. for (int i = 0; i < mapping.Length; i++) {
  300. tableArray[i] = readerArray[mapping[i]];
  301. }
  302. FillErrorEventArgs args = CreateFillErrorEvent (dataTable, tableArray, e);
  303. OnFillError (args);
  304. if(!args.Continue) {
  305. return false;
  306. }
  307. }
  308. }
  309. return true;
  310. }
  311. public override DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType)
  312. {
  313. return FillSchema (dataSet, schemaType, SelectCommand, DefaultSourceTableName, CommandBehavior.Default);
  314. }
  315. public DataTable FillSchema (DataTable dataTable, SchemaType schemaType)
  316. {
  317. return FillSchema (dataTable, schemaType, SelectCommand, CommandBehavior.Default);
  318. }
  319. public DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType, string srcTable)
  320. {
  321. return FillSchema (dataSet, schemaType, SelectCommand, srcTable, CommandBehavior.Default);
  322. }
  323. [MonoTODO ("Verify")]
  324. protected virtual DataTable FillSchema (DataTable dataTable, SchemaType schemaType, IDbCommand command, CommandBehavior behavior)
  325. {
  326. behavior |= CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo;
  327. if (command.Connection.State == ConnectionState.Closed) {
  328. command.Connection.Open ();
  329. behavior |= CommandBehavior.CloseConnection;
  330. }
  331. IDataReader reader = command.ExecuteReader (behavior);
  332. try
  333. {
  334. string tableName = SetupSchema (schemaType, dataTable.TableName);
  335. if (tableName != null)
  336. {
  337. BuildSchema (reader, dataTable, schemaType);
  338. }
  339. }
  340. finally
  341. {
  342. reader.Close ();
  343. }
  344. return dataTable;
  345. }
  346. [MonoTODO ("Verify")]
  347. protected virtual DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType, IDbCommand command, string srcTable, CommandBehavior behavior)
  348. {
  349. behavior |= CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo;
  350. if (command.Connection.State == ConnectionState.Closed) {
  351. command.Connection.Open ();
  352. behavior |= CommandBehavior.CloseConnection;
  353. }
  354. IDataReader reader = command.ExecuteReader (behavior);
  355. ArrayList output = new ArrayList ();
  356. string tableName = srcTable;
  357. int index = 0;
  358. DataTable table;
  359. try
  360. {
  361. tableName = SetupSchema (schemaType, tableName);
  362. if (tableName != null)
  363. {
  364. if (dataSet.Tables.Contains (tableName))
  365. table = dataSet.Tables [tableName];
  366. else
  367. {
  368. table = new DataTable(tableName);
  369. dataSet.Tables.Add (table);
  370. }
  371. BuildSchema (reader, table, schemaType);
  372. output.Add (table);
  373. tableName = String.Format ("{0}{1}", srcTable, ++index);
  374. }
  375. }
  376. finally
  377. {
  378. reader.Close ();
  379. }
  380. return (DataTable[]) output.ToArray (typeof (DataTable));
  381. }
  382. #if NET_2_0
  383. [MonoTODO]
  384. public DataSet GetDataSet ()
  385. {
  386. throw new NotImplementedException ();
  387. }
  388. [MonoTODO]
  389. public DataTable GetDataTable ()
  390. {
  391. throw new NotImplementedException ();
  392. }
  393. #endif
  394. private string SetupSchema (SchemaType schemaType, string sourceTableName)
  395. {
  396. DataTableMapping tableMapping = null;
  397. if (schemaType == SchemaType.Mapped)
  398. {
  399. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, sourceTableName, sourceTableName, MissingMappingAction);
  400. if (tableMapping != null)
  401. return tableMapping.DataSetTable;
  402. return null;
  403. }
  404. else
  405. return sourceTableName;
  406. }
  407. [EditorBrowsable (EditorBrowsableState.Advanced)]
  408. public override IDataParameter[] GetFillParameters ()
  409. {
  410. IDataParameter[] parameters = new IDataParameter[SelectCommand.Parameters.Count];
  411. SelectCommand.Parameters.CopyTo (parameters, 0);
  412. return parameters;
  413. }
  414. // this method builds the schema for a given datatable. it returns a int array with
  415. // "array[ordinal of datatable column] == index of source column in data reader".
  416. // each column in the datatable has a mapping to a specific column in the datareader,
  417. // the int array represents this match.
  418. [MonoTODO ("Test")]
  419. private int[] BuildSchema (IDataReader reader, DataTable table, SchemaType schemaType)
  420. {
  421. int readerIndex = 0;
  422. int[] mapping = new int[reader.FieldCount]; // mapping the reader indexes to the datatable indexes
  423. ArrayList primaryKey = new ArrayList ();
  424. ArrayList sourceColumns = new ArrayList ();
  425. foreach (DataRow schemaRow in reader.GetSchemaTable ().Rows) {
  426. // generate a unique column name in the source table.
  427. string sourceColumnName;
  428. if (schemaRow.IsNull("ColumnName"))
  429. sourceColumnName = DefaultSourceColumnName;
  430. else
  431. sourceColumnName = (string) schemaRow ["ColumnName"];
  432. string realSourceColumnName = sourceColumnName;
  433. for (int i = 1; sourceColumns.Contains (realSourceColumnName); i += 1)
  434. realSourceColumnName = String.Format ("{0}{1}", sourceColumnName, i);
  435. sourceColumns.Add(realSourceColumnName);
  436. // generate DataSetColumnName from DataTableMapping, if any
  437. string dsColumnName = realSourceColumnName;
  438. DataTableMapping tableMapping = null;
  439. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, table.TableName, table.TableName, MissingMappingAction);
  440. if (tableMapping != null)
  441. {
  442. table.TableName = tableMapping.DataSetTable;
  443. // check to see if the column mapping exists
  444. DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction(tableMapping.ColumnMappings, realSourceColumnName, MissingMappingAction);
  445. if (columnMapping != null)
  446. {
  447. DataColumn col =
  448. columnMapping.GetDataColumnBySchemaAction(
  449. table ,
  450. (Type)schemaRow["DataType"],
  451. MissingSchemaAction);
  452. if (col != null)
  453. {
  454. // if the column is not in the table - add it.
  455. if (table.Columns.IndexOf(col) == -1)
  456. {
  457. if (MissingSchemaAction == MissingSchemaAction.Add || MissingSchemaAction == MissingSchemaAction.AddWithKey)
  458. table.Columns.Add(col);
  459. }
  460. if (!schemaRow["IsKey"].Equals (DBNull.Value))
  461. if ((bool) (schemaRow ["IsKey"]))
  462. primaryKey.Add (col);
  463. // add the ordinal of the column as a key and the index of the column in the datareader as a value.
  464. mapping[col.Ordinal] = readerIndex;
  465. }
  466. }
  467. }
  468. readerIndex++;
  469. }
  470. if (primaryKey.Count > 0)
  471. table.PrimaryKey = (DataColumn[])(primaryKey.ToArray(typeof (DataColumn)));
  472. return mapping;
  473. }
  474. [MonoTODO]
  475. object ICloneable.Clone ()
  476. {
  477. throw new NotImplementedException ();
  478. }
  479. [MonoTODO]
  480. public int Update (DataRow[] dataRows)
  481. {
  482. if (dataRows == null)
  483. throw new ArgumentNullException("dataRows");
  484. if (dataRows.Length == 0)
  485. return 0;
  486. if (dataRows[0] == null)
  487. throw new ArgumentException("dataRows[0].");
  488. DataTable table = dataRows[0].Table;
  489. if (table == null)
  490. throw new ArgumentException("table is null reference.");
  491. // all rows must be in the same table
  492. for (int i = 0; i < dataRows.Length; i++)
  493. {
  494. if (dataRows[i] == null)
  495. throw new ArgumentException("dataRows[" + i + "].");
  496. if (dataRows[i].Table != table)
  497. throw new ArgumentException(
  498. " DataRow["
  499. + i
  500. + "] is from a different DataTable than DataRow[0].");
  501. }
  502. // get table mapping for this rows
  503. DataTableMapping tableMapping = TableMappings.GetByDataSetTable(table.TableName);
  504. if (tableMapping == null)
  505. {
  506. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction(
  507. TableMappings,
  508. table.TableName,
  509. table.TableName,
  510. MissingMappingAction);
  511. if (tableMapping != null) {
  512. foreach (DataColumn col in table.Columns) {
  513. if (tableMapping.ColumnMappings.IndexOf (col.ColumnName) >= 0)
  514. continue;
  515. DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction (tableMapping.ColumnMappings, col.ColumnName, MissingMappingAction);
  516. if (columnMapping == null)
  517. columnMapping = new DataColumnMapping (col.ColumnName, col.ColumnName);
  518. tableMapping.ColumnMappings.Add (columnMapping);
  519. }
  520. } else {
  521. ArrayList cmc = new ArrayList ();
  522. foreach (DataColumn col in table.Columns)
  523. cmc.Add (new DataColumnMapping (col.ColumnName, col.ColumnName));
  524. tableMapping =
  525. new DataTableMapping (
  526. table.TableName,
  527. table.TableName,
  528. cmc.ToArray (typeof (DataColumnMapping)) as DataColumnMapping []);
  529. }
  530. }
  531. DataRow[] copy = new DataRow [dataRows.Length];
  532. Array.Copy(dataRows, 0, copy, 0, dataRows.Length);
  533. return Update(copy, tableMapping);
  534. }
  535. public override int Update (DataSet dataSet)
  536. {
  537. return Update (dataSet, DefaultSourceTableName);
  538. }
  539. public int Update (DataTable dataTable)
  540. {
  541. /*
  542. int index = TableMappings.IndexOfDataSetTable (dataTable.TableName);
  543. if (index < 0)
  544. throw new ArgumentException ();
  545. return Update (dataTable, TableMappings [index]);
  546. */
  547. DataTableMapping tableMapping = TableMappings.GetByDataSetTable (dataTable.TableName);
  548. if (tableMapping == null)
  549. {
  550. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (
  551. TableMappings,
  552. dataTable.TableName,
  553. dataTable.TableName,
  554. MissingMappingAction);
  555. if (tableMapping != null) {
  556. foreach (DataColumn col in dataTable.Columns) {
  557. if (tableMapping.ColumnMappings.IndexOf (col.ColumnName) >= 0)
  558. continue;
  559. DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction (tableMapping.ColumnMappings, col.ColumnName, MissingMappingAction);
  560. if (columnMapping == null)
  561. columnMapping = new DataColumnMapping (col.ColumnName, col.ColumnName);
  562. tableMapping.ColumnMappings.Add (columnMapping);
  563. }
  564. } else {
  565. ArrayList cmc = new ArrayList ();
  566. foreach (DataColumn col in dataTable.Columns)
  567. cmc.Add (new DataColumnMapping (col.ColumnName, col.ColumnName));
  568. tableMapping =
  569. new DataTableMapping (
  570. dataTable.TableName,
  571. dataTable.TableName,
  572. cmc.ToArray (typeof (DataColumnMapping)) as DataColumnMapping []);
  573. }
  574. }
  575. return Update (dataTable, tableMapping);
  576. }
  577. private int Update (DataTable dataTable, DataTableMapping tableMapping)
  578. {
  579. DataRow[] rows = new DataRow [dataTable.Rows.Count];
  580. dataTable.Rows.CopyTo (rows, 0);
  581. return Update (rows, tableMapping);
  582. }
  583. [MonoTODO]
  584. protected virtual int Update (DataRow[] dataRows, DataTableMapping tableMapping)
  585. {
  586. int updateCount = 0;
  587. foreach (DataRow row in dataRows) {
  588. StatementType statementType = StatementType.Update;
  589. IDbCommand command = null;
  590. string commandName = String.Empty;
  591. bool useCommandBuilder = false;
  592. switch (row.RowState) {
  593. case DataRowState.Added:
  594. statementType = StatementType.Insert;
  595. command = InsertCommand;
  596. commandName = "Insert";
  597. break;
  598. case DataRowState.Deleted:
  599. statementType = StatementType.Delete;
  600. command = DeleteCommand;
  601. commandName = "Delete";
  602. break;
  603. case DataRowState.Modified:
  604. statementType = StatementType.Update;
  605. command = UpdateCommand;
  606. commandName = "Update";
  607. break;
  608. case DataRowState.Unchanged:
  609. continue;
  610. case DataRowState.Detached:
  611. throw new NotImplementedException ();
  612. }
  613. if (command == null)
  614. useCommandBuilder = true;
  615. RowUpdatingEventArgs args = CreateRowUpdatingEvent (row, command, statementType, tableMapping);
  616. OnRowUpdating (args);
  617. if (args.Status == UpdateStatus.ErrorsOccurred)
  618. throw (args.Errors);
  619. if (command == null && args.Command != null)
  620. command = args.Command;
  621. else if (command == null)
  622. throw new InvalidOperationException (String.Format ("Update requires a valid {0}Command when passed a DataRow collection with modified rows.", commandName));
  623. if (!useCommandBuilder) {
  624. DataColumnMappingCollection columnMappings = tableMapping.ColumnMappings;
  625. foreach (IDataParameter parameter in command.Parameters) {
  626. string dsColumnName = parameter.SourceColumn;
  627. if (columnMappings.Contains(parameter.SourceColumn))
  628. dsColumnName = columnMappings [parameter.SourceColumn].DataSetColumn;
  629. DataRowVersion rowVersion = DataRowVersion.Default;
  630. // Parameter version is ignored for non-update commands
  631. if (statementType == StatementType.Update)
  632. rowVersion = parameter.SourceVersion;
  633. if (statementType == StatementType.Delete)
  634. rowVersion = DataRowVersion.Original;
  635. parameter.Value = row [dsColumnName, rowVersion];
  636. }
  637. }
  638. CommandBehavior commandBehavior = CommandBehavior.Default;
  639. if (command.Connection.State == ConnectionState.Closed)
  640. {
  641. command.Connection.Open ();
  642. commandBehavior |= CommandBehavior.CloseConnection;
  643. }
  644. IDataReader reader = null;
  645. try
  646. {
  647. // use ExecuteReader because we want to use the commandbehavior parameter.
  648. // so the connection will be closed if needed.
  649. reader = command.ExecuteReader (commandBehavior);
  650. int tmp = reader.RecordsAffected;
  651. // if the execute does not effect any rows we throw an exception.
  652. if (tmp == 0)
  653. throw new DBConcurrencyException("Concurrency violation: the " + commandName +"Command affected 0 records.");
  654. updateCount += tmp;
  655. OnRowUpdated (CreateRowUpdatedEvent (row, command, statementType, tableMapping));
  656. row.AcceptChanges ();
  657. }
  658. catch (Exception e)
  659. {
  660. if (ContinueUpdateOnError)
  661. row.RowError = e.Message;// do somthing with the error
  662. else
  663. throw e;
  664. }
  665. finally
  666. {
  667. if (reader != null)
  668. reader.Close ();
  669. }
  670. }
  671. return updateCount;
  672. }
  673. public int Update (DataSet dataSet, string sourceTable)
  674. {
  675. MissingMappingAction mappingAction = MissingMappingAction;
  676. if (mappingAction == MissingMappingAction.Ignore)
  677. mappingAction = MissingMappingAction.Error;
  678. DataTableMapping tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, sourceTable, sourceTable, mappingAction);
  679. DataTable dataTable = dataSet.Tables[tableMapping.DataSetTable];
  680. if (dataTable == null)
  681. throw new ArgumentException ("sourceTable");
  682. return Update (dataTable, tableMapping);
  683. }
  684. #if ONLY_1_0 || ONLY_1_1
  685. protected virtual void OnFillError (FillErrorEventArgs value)
  686. {
  687. if (FillError != null)
  688. FillError (this, value);
  689. }
  690. #endif
  691. protected abstract void OnRowUpdated (RowUpdatedEventArgs value);
  692. protected abstract void OnRowUpdating (RowUpdatingEventArgs value);
  693. #endregion // Methods
  694. }
  695. }