2
0

DbDataAdapter.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  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. // Non-resultset queries like insert, delete or update aren't processed.
  242. if (dataReader.FieldCount != -1)
  243. {
  244. tableName = SetupSchema (SchemaType.Mapped, tableName);
  245. if (tableName != null) {
  246. // check if the table exists in the dataset
  247. if (dataSet.Tables.Contains (tableName))
  248. // get the table from the dataset
  249. dataTable = dataSet.Tables [tableName];
  250. else {
  251. dataTable = new DataTable(tableName);
  252. dataSet.Tables.Add (dataTable);
  253. }
  254. if (!FillTable (dataTable, dataReader, startRecord, maxRecords, ref count)) {
  255. continue;
  256. }
  257. tableName = String.Format ("{0}{1}", srcTable, ++resultIndex);
  258. startRecord = 0;
  259. maxRecords = 0;
  260. }
  261. }
  262. } while (dataReader.NextResult ());
  263. }
  264. finally {
  265. dataReader.Close ();
  266. }
  267. return count;
  268. }
  269. protected virtual int Fill (DataSet dataSet, int startRecord, int maxRecords, string srcTable, IDbCommand command, CommandBehavior behavior)
  270. {
  271. if (MissingSchemaAction == MissingSchemaAction.AddWithKey)
  272. behavior |= CommandBehavior.KeyInfo;
  273. CommandBehavior commandBehavior = behavior;
  274. if (command.Connection.State == ConnectionState.Closed) {
  275. command.Connection.Open ();
  276. commandBehavior |= CommandBehavior.CloseConnection;
  277. }
  278. return Fill (dataSet, srcTable, command.ExecuteReader (commandBehavior), startRecord, maxRecords);
  279. }
  280. private bool FillTable (DataTable dataTable, IDataReader dataReader, int startRecord, int maxRecords, ref int counter)
  281. {
  282. if (dataReader.FieldCount == 0) {
  283. return false;
  284. }
  285. int counterStart = counter;
  286. int[] mapping = BuildSchema (dataReader, dataTable, SchemaType.Mapped);
  287. for (int i = 0; i < startRecord; i++) {
  288. dataReader.Read ();
  289. }
  290. while (dataReader.Read () && (maxRecords == 0 || (counter - counterStart) < maxRecords)) {
  291. try {
  292. dataTable.BeginLoadData ();
  293. dataTable.LoadDataRow (dataReader, mapping, AcceptChangesDuringFill);
  294. dataTable.EndLoadData ();
  295. counter++;
  296. }
  297. catch (Exception e) {
  298. object[] readerArray = new object[dataReader.FieldCount];
  299. object[] tableArray = new object[mapping.Length];
  300. // we get the values from the datareader
  301. dataReader.GetValues (readerArray);
  302. // copy from datareader columns to table columns according to given mapping
  303. for (int i = 0; i < mapping.Length; i++) {
  304. tableArray[i] = readerArray[mapping[i]];
  305. }
  306. FillErrorEventArgs args = CreateFillErrorEvent (dataTable, tableArray, e);
  307. OnFillError (args);
  308. if(!args.Continue) {
  309. return false;
  310. }
  311. }
  312. }
  313. return true;
  314. }
  315. public override DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType)
  316. {
  317. return FillSchema (dataSet, schemaType, SelectCommand, DefaultSourceTableName, CommandBehavior.Default);
  318. }
  319. public DataTable FillSchema (DataTable dataTable, SchemaType schemaType)
  320. {
  321. return FillSchema (dataTable, schemaType, SelectCommand, CommandBehavior.Default);
  322. }
  323. public DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType, string srcTable)
  324. {
  325. return FillSchema (dataSet, schemaType, SelectCommand, srcTable, CommandBehavior.Default);
  326. }
  327. [MonoTODO ("Verify")]
  328. protected virtual DataTable FillSchema (DataTable dataTable, SchemaType schemaType, IDbCommand command, CommandBehavior behavior)
  329. {
  330. behavior |= CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo;
  331. if (command.Connection.State == ConnectionState.Closed) {
  332. command.Connection.Open ();
  333. behavior |= CommandBehavior.CloseConnection;
  334. }
  335. IDataReader reader = command.ExecuteReader (behavior);
  336. try
  337. {
  338. string tableName = SetupSchema (schemaType, dataTable.TableName);
  339. if (tableName != null)
  340. {
  341. BuildSchema (reader, dataTable, schemaType);
  342. }
  343. }
  344. finally
  345. {
  346. reader.Close ();
  347. }
  348. return dataTable;
  349. }
  350. [MonoTODO ("Verify")]
  351. protected virtual DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType, IDbCommand command, string srcTable, CommandBehavior behavior)
  352. {
  353. behavior |= CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo;
  354. if (command.Connection.State == ConnectionState.Closed) {
  355. command.Connection.Open ();
  356. behavior |= CommandBehavior.CloseConnection;
  357. }
  358. IDataReader reader = command.ExecuteReader (behavior);
  359. ArrayList output = new ArrayList ();
  360. string tableName = srcTable;
  361. int index = 0;
  362. DataTable table;
  363. try
  364. {
  365. tableName = SetupSchema (schemaType, tableName);
  366. if (tableName != null)
  367. {
  368. if (dataSet.Tables.Contains (tableName))
  369. table = dataSet.Tables [tableName];
  370. else
  371. {
  372. table = new DataTable(tableName);
  373. dataSet.Tables.Add (table);
  374. }
  375. BuildSchema (reader, table, schemaType);
  376. output.Add (table);
  377. tableName = String.Format ("{0}{1}", srcTable, ++index);
  378. }
  379. }
  380. finally
  381. {
  382. reader.Close ();
  383. }
  384. return (DataTable[]) output.ToArray (typeof (DataTable));
  385. }
  386. #if NET_2_0
  387. [MonoTODO]
  388. public DataSet GetDataSet ()
  389. {
  390. throw new NotImplementedException ();
  391. }
  392. [MonoTODO]
  393. public DataTable GetDataTable ()
  394. {
  395. throw new NotImplementedException ();
  396. }
  397. #endif
  398. private string SetupSchema (SchemaType schemaType, string sourceTableName)
  399. {
  400. DataTableMapping tableMapping = null;
  401. if (schemaType == SchemaType.Mapped)
  402. {
  403. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, sourceTableName, sourceTableName, MissingMappingAction);
  404. if (tableMapping != null)
  405. return tableMapping.DataSetTable;
  406. return null;
  407. }
  408. else
  409. return sourceTableName;
  410. }
  411. [EditorBrowsable (EditorBrowsableState.Advanced)]
  412. public override IDataParameter[] GetFillParameters ()
  413. {
  414. IDataParameter[] parameters = new IDataParameter[SelectCommand.Parameters.Count];
  415. SelectCommand.Parameters.CopyTo (parameters, 0);
  416. return parameters;
  417. }
  418. // this method builds the schema for a given datatable. it returns a int array with
  419. // "array[ordinal of datatable column] == index of source column in data reader".
  420. // each column in the datatable has a mapping to a specific column in the datareader,
  421. // the int array represents this match.
  422. [MonoTODO ("Test")]
  423. private int[] BuildSchema (IDataReader reader, DataTable table, SchemaType schemaType)
  424. {
  425. int readerIndex = 0;
  426. int[] mapping = new int[reader.FieldCount]; // mapping the reader indexes to the datatable indexes
  427. ArrayList primaryKey = new ArrayList ();
  428. ArrayList sourceColumns = new ArrayList ();
  429. foreach (DataRow schemaRow in reader.GetSchemaTable ().Rows) {
  430. // generate a unique column name in the source table.
  431. string sourceColumnName;
  432. if (schemaRow.IsNull("ColumnName"))
  433. sourceColumnName = DefaultSourceColumnName;
  434. else
  435. sourceColumnName = (string) schemaRow ["ColumnName"];
  436. string realSourceColumnName = sourceColumnName;
  437. for (int i = 1; sourceColumns.Contains (realSourceColumnName); i += 1)
  438. realSourceColumnName = String.Format ("{0}{1}", sourceColumnName, i);
  439. sourceColumns.Add(realSourceColumnName);
  440. // generate DataSetColumnName from DataTableMapping, if any
  441. string dsColumnName = realSourceColumnName;
  442. DataTableMapping tableMapping = null;
  443. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, table.TableName, table.TableName, MissingMappingAction);
  444. if (tableMapping != null)
  445. {
  446. table.TableName = tableMapping.DataSetTable;
  447. // check to see if the column mapping exists
  448. DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction(tableMapping.ColumnMappings, realSourceColumnName, MissingMappingAction);
  449. if (columnMapping != null)
  450. {
  451. DataColumn col =
  452. columnMapping.GetDataColumnBySchemaAction(
  453. table ,
  454. (Type)schemaRow["DataType"],
  455. MissingSchemaAction);
  456. if (col != null)
  457. {
  458. // if the column is not in the table - add it.
  459. if (table.Columns.IndexOf(col) == -1)
  460. {
  461. if (MissingSchemaAction == MissingSchemaAction.Add || MissingSchemaAction == MissingSchemaAction.AddWithKey)
  462. table.Columns.Add(col);
  463. }
  464. if (!schemaRow["IsKey"].Equals (DBNull.Value))
  465. if ((bool) (schemaRow ["IsKey"]))
  466. primaryKey.Add (col);
  467. // add the ordinal of the column as a key and the index of the column in the datareader as a value.
  468. mapping[col.Ordinal] = readerIndex;
  469. }
  470. }
  471. }
  472. readerIndex++;
  473. }
  474. if (primaryKey.Count > 0)
  475. table.PrimaryKey = (DataColumn[])(primaryKey.ToArray(typeof (DataColumn)));
  476. return mapping;
  477. }
  478. [MonoTODO]
  479. object ICloneable.Clone ()
  480. {
  481. throw new NotImplementedException ();
  482. }
  483. [MonoTODO]
  484. public int Update (DataRow[] dataRows)
  485. {
  486. if (dataRows == null)
  487. throw new ArgumentNullException("dataRows");
  488. if (dataRows.Length == 0)
  489. return 0;
  490. if (dataRows[0] == null)
  491. throw new ArgumentException("dataRows[0].");
  492. DataTable table = dataRows[0].Table;
  493. if (table == null)
  494. throw new ArgumentException("table is null reference.");
  495. // all rows must be in the same table
  496. for (int i = 0; i < dataRows.Length; i++)
  497. {
  498. if (dataRows[i] == null)
  499. throw new ArgumentException("dataRows[" + i + "].");
  500. if (dataRows[i].Table != table)
  501. throw new ArgumentException(
  502. " DataRow["
  503. + i
  504. + "] is from a different DataTable than DataRow[0].");
  505. }
  506. // get table mapping for this rows
  507. DataTableMapping tableMapping = TableMappings.GetByDataSetTable(table.TableName);
  508. if (tableMapping == null)
  509. {
  510. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction(
  511. TableMappings,
  512. table.TableName,
  513. table.TableName,
  514. MissingMappingAction);
  515. if (tableMapping != null) {
  516. foreach (DataColumn col in table.Columns) {
  517. if (tableMapping.ColumnMappings.IndexOf (col.ColumnName) >= 0)
  518. continue;
  519. DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction (tableMapping.ColumnMappings, col.ColumnName, MissingMappingAction);
  520. if (columnMapping == null)
  521. columnMapping = new DataColumnMapping (col.ColumnName, col.ColumnName);
  522. tableMapping.ColumnMappings.Add (columnMapping);
  523. }
  524. } else {
  525. ArrayList cmc = new ArrayList ();
  526. foreach (DataColumn col in table.Columns)
  527. cmc.Add (new DataColumnMapping (col.ColumnName, col.ColumnName));
  528. tableMapping =
  529. new DataTableMapping (
  530. table.TableName,
  531. table.TableName,
  532. cmc.ToArray (typeof (DataColumnMapping)) as DataColumnMapping []);
  533. }
  534. }
  535. DataRow[] copy = new DataRow [dataRows.Length];
  536. Array.Copy(dataRows, 0, copy, 0, dataRows.Length);
  537. return Update(copy, tableMapping);
  538. }
  539. public override int Update (DataSet dataSet)
  540. {
  541. return Update (dataSet, DefaultSourceTableName);
  542. }
  543. public int Update (DataTable dataTable)
  544. {
  545. /*
  546. int index = TableMappings.IndexOfDataSetTable (dataTable.TableName);
  547. if (index < 0)
  548. throw new ArgumentException ();
  549. return Update (dataTable, TableMappings [index]);
  550. */
  551. DataTableMapping tableMapping = TableMappings.GetByDataSetTable (dataTable.TableName);
  552. if (tableMapping == null)
  553. {
  554. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (
  555. TableMappings,
  556. dataTable.TableName,
  557. dataTable.TableName,
  558. MissingMappingAction);
  559. if (tableMapping != null) {
  560. foreach (DataColumn col in dataTable.Columns) {
  561. if (tableMapping.ColumnMappings.IndexOf (col.ColumnName) >= 0)
  562. continue;
  563. DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction (tableMapping.ColumnMappings, col.ColumnName, MissingMappingAction);
  564. if (columnMapping == null)
  565. columnMapping = new DataColumnMapping (col.ColumnName, col.ColumnName);
  566. tableMapping.ColumnMappings.Add (columnMapping);
  567. }
  568. } else {
  569. ArrayList cmc = new ArrayList ();
  570. foreach (DataColumn col in dataTable.Columns)
  571. cmc.Add (new DataColumnMapping (col.ColumnName, col.ColumnName));
  572. tableMapping =
  573. new DataTableMapping (
  574. dataTable.TableName,
  575. dataTable.TableName,
  576. cmc.ToArray (typeof (DataColumnMapping)) as DataColumnMapping []);
  577. }
  578. }
  579. return Update (dataTable, tableMapping);
  580. }
  581. private int Update (DataTable dataTable, DataTableMapping tableMapping)
  582. {
  583. DataRow[] rows = new DataRow [dataTable.Rows.Count];
  584. dataTable.Rows.CopyTo (rows, 0);
  585. return Update (rows, tableMapping);
  586. }
  587. [MonoTODO]
  588. protected virtual int Update (DataRow[] dataRows, DataTableMapping tableMapping)
  589. {
  590. int updateCount = 0;
  591. foreach (DataRow row in dataRows) {
  592. StatementType statementType = StatementType.Update;
  593. IDbCommand command = null;
  594. string commandName = String.Empty;
  595. bool useCommandBuilder = false;
  596. switch (row.RowState) {
  597. case DataRowState.Added:
  598. statementType = StatementType.Insert;
  599. command = InsertCommand;
  600. commandName = "Insert";
  601. break;
  602. case DataRowState.Deleted:
  603. statementType = StatementType.Delete;
  604. command = DeleteCommand;
  605. commandName = "Delete";
  606. break;
  607. case DataRowState.Modified:
  608. statementType = StatementType.Update;
  609. command = UpdateCommand;
  610. commandName = "Update";
  611. break;
  612. case DataRowState.Unchanged:
  613. continue;
  614. case DataRowState.Detached:
  615. throw new NotImplementedException ();
  616. }
  617. if (command == null)
  618. useCommandBuilder = true;
  619. RowUpdatingEventArgs args = CreateRowUpdatingEvent (row, command, statementType, tableMapping);
  620. OnRowUpdating (args);
  621. if (args.Status == UpdateStatus.ErrorsOccurred)
  622. throw (args.Errors);
  623. if (command == null && args.Command != null)
  624. command = args.Command;
  625. else if (command == null)
  626. throw new InvalidOperationException (String.Format ("Update requires a valid {0}Command when passed a DataRow collection with modified rows.", commandName));
  627. if (!useCommandBuilder) {
  628. DataColumnMappingCollection columnMappings = tableMapping.ColumnMappings;
  629. foreach (IDataParameter parameter in command.Parameters) {
  630. string dsColumnName = parameter.SourceColumn;
  631. if (columnMappings.Contains(parameter.SourceColumn))
  632. dsColumnName = columnMappings [parameter.SourceColumn].DataSetColumn;
  633. DataRowVersion rowVersion = DataRowVersion.Default;
  634. // Parameter version is ignored for non-update commands
  635. if (statementType == StatementType.Update)
  636. rowVersion = parameter.SourceVersion;
  637. if (statementType == StatementType.Delete)
  638. rowVersion = DataRowVersion.Original;
  639. parameter.Value = row [dsColumnName, rowVersion];
  640. }
  641. }
  642. CommandBehavior commandBehavior = CommandBehavior.Default;
  643. if (command.Connection.State == ConnectionState.Closed)
  644. {
  645. command.Connection.Open ();
  646. commandBehavior |= CommandBehavior.CloseConnection;
  647. }
  648. IDataReader reader = null;
  649. try
  650. {
  651. // use ExecuteReader because we want to use the commandbehavior parameter.
  652. // so the connection will be closed if needed.
  653. reader = command.ExecuteReader (commandBehavior);
  654. int tmp = reader.RecordsAffected;
  655. // if the execute does not effect any rows we throw an exception.
  656. if (tmp == 0)
  657. throw new DBConcurrencyException("Concurrency violation: the " + commandName +"Command affected 0 records.");
  658. updateCount += tmp;
  659. OnRowUpdated (CreateRowUpdatedEvent (row, command, statementType, tableMapping));
  660. row.AcceptChanges ();
  661. }
  662. catch (Exception e)
  663. {
  664. if (ContinueUpdateOnError)
  665. row.RowError = e.Message;// do somthing with the error
  666. else
  667. throw e;
  668. }
  669. finally
  670. {
  671. if (reader != null)
  672. reader.Close ();
  673. }
  674. }
  675. return updateCount;
  676. }
  677. public int Update (DataSet dataSet, string sourceTable)
  678. {
  679. MissingMappingAction mappingAction = MissingMappingAction;
  680. if (mappingAction == MissingMappingAction.Ignore)
  681. mappingAction = MissingMappingAction.Error;
  682. DataTableMapping tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, sourceTable, sourceTable, mappingAction);
  683. DataTable dataTable = dataSet.Tables[tableMapping.DataSetTable];
  684. if (dataTable == null)
  685. throw new ArgumentException ("sourceTable");
  686. return Update (dataTable, tableMapping);
  687. }
  688. #if ONLY_1_0 || ONLY_1_1
  689. protected virtual void OnFillError (FillErrorEventArgs value)
  690. {
  691. if (FillError != null)
  692. FillError (this, value);
  693. }
  694. #endif
  695. protected abstract void OnRowUpdated (RowUpdatedEventArgs value);
  696. protected abstract void OnRowUpdating (RowUpdatingEventArgs value);
  697. #endregion // Methods
  698. }
  699. }