/// <summary> /// Inserts a School.Entities.Students object into the datasource using a transaction. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="entity">School.Entities.Students object to insert.</param> /// <remarks> /// After inserting into the datasource, the School.Entities.Students object will be updated /// to refelect any changes made by the datasource. (ie: identity or computed columns) /// </remarks> /// <returns>Returns true if operation is successful.</returns> /// <exception cref="System.Exception">The command could not be executed.</exception> /// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception> /// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception> public override bool Insert(TransactionManager transactionManager, School.Entities.Students entity) { SqlDatabase database = new SqlDatabase(this._connectionString); DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "dbo.Students_Insert", _useStoredProcedure); database.AddOutParameter(commandWrapper, "@Id", DbType.Int32, 4); database.AddInParameter(commandWrapper, "@Name", DbType.String, entity.Name ); database.AddInParameter(commandWrapper, "@Address", DbType.String, entity.Address ); database.AddInParameter(commandWrapper, "@ClassId", DbType.Int32, entity.ClassId ); database.AddInParameter(commandWrapper, "@Birthdate", DbType.Date, entity.Birthdate ); database.AddInParameter(commandWrapper, "@Gender", DbType.String, entity.Gender ); int results = 0; //Provider Data Requesting Command Event OnDataRequesting(new CommandEventArgs(commandWrapper, "Insert", entity)); if (transactionManager != null) { results = Utility.ExecuteNonQuery(transactionManager, commandWrapper); } else { results = Utility.ExecuteNonQuery(database,commandWrapper); } object _id = database.GetParameterValue(commandWrapper, "@Id"); entity.Id = (System.Int32)_id; entity.AcceptChanges(); //Provider Data Requested Command Event OnDataRequested(new CommandEventArgs(commandWrapper, "Insert", entity)); return Convert.ToBoolean(results); }
/// <summary> /// Update an existing row in the datasource. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="entity">School.Entities.Students object to update.</param> /// <remarks> /// After updating the datasource, the School.Entities.Students object will be updated /// to refelect any changes made by the datasource. (ie: identity or computed columns) /// </remarks> /// <returns>Returns true if operation is successful.</returns> /// <exception cref="System.Exception">The command could not be executed.</exception> /// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception> /// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception> public override bool Update(TransactionManager transactionManager, School.Entities.Students entity) { SqlDatabase database = new SqlDatabase(this._connectionString); DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "dbo.Students_Update", _useStoredProcedure); database.AddInParameter(commandWrapper, "@Id", DbType.Int32, entity.Id ); database.AddInParameter(commandWrapper, "@Name", DbType.String, entity.Name ); database.AddInParameter(commandWrapper, "@Address", DbType.String, entity.Address ); database.AddInParameter(commandWrapper, "@ClassId", DbType.Int32, entity.ClassId ); database.AddInParameter(commandWrapper, "@Birthdate", DbType.Date, entity.Birthdate ); database.AddInParameter(commandWrapper, "@Gender", DbType.String, entity.Gender ); int results = 0; //Provider Data Requesting Command Event OnDataRequesting(new CommandEventArgs(commandWrapper, "Update", entity)); if (transactionManager != null) { results = Utility.ExecuteNonQuery(transactionManager, commandWrapper); } else { results = Utility.ExecuteNonQuery(database,commandWrapper); } //Stop Tracking Now that it has been updated and persisted. if (DataRepository.Provider.EnableEntityTracking) { EntityManager.StopTracking(entity.EntityTrackingKey); } entity.AcceptChanges(); //Provider Data Requested Command Event OnDataRequested(new CommandEventArgs(commandWrapper, "Update", entity)); return Convert.ToBoolean(results); }
/// <summary> /// Gets rows from the datasource based on the PK_Students index. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="_id"></param> /// <param name="start">Row number at which to start reading.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="count">out parameter to get total records for query.</param> /// <returns>Returns an instance of the <see cref="School.Entities.Students"/> class.</returns> /// <remarks></remarks> /// <exception cref="System.Exception">The command could not be executed.</exception> /// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception> /// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception> public override School.Entities.Students GetById(TransactionManager transactionManager, System.Int32 _id, int start, int pageLength, out int count) { SqlDatabase database = new SqlDatabase(this._connectionString); DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "dbo.Students_GetById", _useStoredProcedure); database.AddInParameter(commandWrapper, "@Id", DbType.Int32, _id); IDataReader reader = null; TList<Students> tmp = new TList<Students>(); try { //Provider Data Requesting Command Event OnDataRequesting(new CommandEventArgs(commandWrapper, "GetById", tmp)); if (transactionManager != null) { reader = Utility.ExecuteReader(transactionManager, commandWrapper); } else { reader = Utility.ExecuteReader(database, commandWrapper); } //Create collection and fill Fill(reader, tmp, start, pageLength); count = -1; if(reader.NextResult()) { if(reader.Read()) { count = reader.GetInt32(0); } } //Provider Data Requested Command Event OnDataRequested(new CommandEventArgs(commandWrapper, "GetById", tmp)); } finally { if (reader != null) reader.Close(); commandWrapper = null; } if (tmp.Count == 1) { return tmp[0]; } else if (tmp.Count == 0) { return null; } else { throw new DataException("Cannot find the unique instance of the class."); } //return rows; }
/// <summary> /// Gets a page of rows from the DataSource. /// </summary> /// <param name="start">Row number at which to start reading.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="count">Number of rows in the DataSource.</param> /// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param> /// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <remarks></remarks> /// <returns>Returns a typed collection of School.Entities.Students objects.</returns> public override TList<Students> GetPaged(TransactionManager transactionManager, string whereClause, string orderBy, int start, int pageLength, out int count) { SqlDatabase database = new SqlDatabase(this._connectionString); DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "dbo.Students_GetPaged", _useStoredProcedure); if (commandWrapper.CommandType == CommandType.Text && commandWrapper.CommandText != null) { commandWrapper.CommandText = commandWrapper.CommandText.Replace(SqlUtil.PAGE_INDEX, string.Concat(SqlUtil.PAGE_INDEX, Guid.NewGuid().ToString("N").Substring(0, 8))); } database.AddInParameter(commandWrapper, "@WhereClause", DbType.String, whereClause); database.AddInParameter(commandWrapper, "@OrderBy", DbType.String, orderBy); database.AddInParameter(commandWrapper, "@PageIndex", DbType.Int32, start); database.AddInParameter(commandWrapper, "@PageSize", DbType.Int32, pageLength); IDataReader reader = null; //Create Collection TList<Students> rows = new TList<Students>(); try { //Provider Data Requesting Command Event OnDataRequesting(new CommandEventArgs(commandWrapper, "GetPaged", rows)); if (transactionManager != null) { reader = Utility.ExecuteReader(transactionManager, commandWrapper); } else { reader = Utility.ExecuteReader(database, commandWrapper); } Fill(reader, rows, 0, int.MaxValue); count = rows.Count; if(reader.NextResult()) { if(reader.Read()) { count = reader.GetInt32(0); } } //Provider Data Requested Command Event OnDataRequested(new CommandEventArgs(commandWrapper, "GetPaged", rows)); } catch(Exception) { throw; } finally { if (reader != null) reader.Close(); commandWrapper = null; } return rows; }
/// <summary> /// Returns rows from the DataSource that meet the parameter conditions. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="parameters">A collection of <see cref="SqlFilterParameter"/> objects.</param> /// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param> /// <param name="start">Row number at which to start reading.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="count">out. The number of rows that match this query.</param> /// <returns>Returns a typed collection of School.Entities.Students objects.</returns> public override TList<Students> Find(TransactionManager transactionManager, IFilterParameterCollection parameters, string orderBy, int start, int pageLength, out int count) { SqlFilterParameterCollection filter = null; if (parameters == null) filter = new SqlFilterParameterCollection(); else filter = parameters.GetParameters(); SqlDatabase database = new SqlDatabase(this._connectionString); DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "dbo.Students_Find_Dynamic", typeof(StudentsColumn), filter, orderBy, start, pageLength); SqlFilterParameter param; for ( int i = 0; i < filter.Count; i++ ) { param = filter[i]; database.AddInParameter(commandWrapper, param.Name, param.DbType, param.GetValue()); } TList<Students> rows = new TList<Students>(); IDataReader reader = null; try { //Provider Data Requesting Command Event OnDataRequesting(new CommandEventArgs(commandWrapper, "Find", rows)); if ( transactionManager != null ) { reader = Utility.ExecuteReader(transactionManager, commandWrapper); } else { reader = Utility.ExecuteReader(database, commandWrapper); } Fill(reader, rows, 0, int.MaxValue); count = rows.Count; if ( reader.NextResult() ) { if ( reader.Read() ) { count = reader.GetInt32(0); } } //Provider Data Requested Command Event OnDataRequested(new CommandEventArgs(commandWrapper, "Find", rows)); } finally { if ( reader != null ) reader.Close(); commandWrapper = null; } return rows; }
/// <summary> /// Gets rows from the datasource based on the FK_Students_Classes1 key. /// FK_Students_Classes1 Description: /// </summary> /// <param name="start">Row number at which to start reading.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="_classId"></param> /// <param name="count">out parameter to get total records for query</param> /// <remarks></remarks> /// <returns>Returns a typed collection of School.Entities.Students objects.</returns> /// <exception cref="System.Exception">The command could not be executed.</exception> /// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception> /// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception> public override TList<Students> GetByClassId(TransactionManager transactionManager, System.Int32 _classId, int start, int pageLength, out int count) { SqlDatabase database = new SqlDatabase(this._connectionString); DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "dbo.Students_GetByClassId", _useStoredProcedure); database.AddInParameter(commandWrapper, "@ClassId", DbType.Int32, _classId); IDataReader reader = null; TList<Students> rows = new TList<Students>(); try { //Provider Data Requesting Command Event OnDataRequesting(new CommandEventArgs(commandWrapper, "GetByClassId", rows)); if (transactionManager != null) { reader = Utility.ExecuteReader(transactionManager, commandWrapper); } else { reader = Utility.ExecuteReader(database, commandWrapper); } //Create Collection Fill(reader, rows, start, pageLength); count = -1; if(reader.NextResult()) { if(reader.Read()) { count = reader.GetInt32(0); } } //Provider Data Requested Command Event OnDataRequested(new CommandEventArgs(commandWrapper, "GetByClassId", rows)); } finally { if (reader != null) reader.Close(); commandWrapper = null; } return rows; }
/// <summary> /// Deletes a row from the DataSource. /// </summary> /// <param name="_id">. Primary Key.</param> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <remarks>Deletes based on primary key(s).</remarks> /// <returns>Returns true if operation suceeded.</returns> /// <exception cref="System.Exception">The command could not be executed.</exception> /// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception> /// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception> public override bool Delete(TransactionManager transactionManager, System.Int32 _id) { SqlDatabase database = new SqlDatabase(this._connectionString); DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "dbo.Students_Delete", _useStoredProcedure); database.AddInParameter(commandWrapper, "@Id", DbType.Int32, _id); //Provider Data Requesting Command Event OnDataRequesting(new CommandEventArgs(commandWrapper, "Delete")); int results = 0; if (transactionManager != null) { results = Utility.ExecuteNonQuery(transactionManager, commandWrapper); } else { results = Utility.ExecuteNonQuery(database,commandWrapper); } //Stop Tracking Now that it has been updated and persisted. if (DataRepository.Provider.EnableEntityTracking) { string entityKey = EntityLocator.ConstructKeyFromPkItems(typeof(Students) ,_id); EntityManager.StopTracking(entityKey); } //Provider Data Requested Command Event OnDataRequested(new CommandEventArgs(commandWrapper, "Delete")); commandWrapper = null; return Convert.ToBoolean(results); }
/// <summary> /// Returns rows meeting the whereClause condition from the DataSource. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param> /// <param name="start">Row number at which to start reading.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="count">out. The number of rows that match this query.</param> /// <remarks>Operators must be capitalized (OR, AND).</remarks> /// <returns>Returns a typed collection of School.Entities.Students objects.</returns> public override TList<Students> Find(TransactionManager transactionManager, string whereClause, int start, int pageLength, out int count) { count = -1; if (whereClause.IndexOf(";") > -1) return new TList<Students>(); SqlDatabase database = new SqlDatabase(this._connectionString); DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "dbo.Students_Find", _useStoredProcedure); bool searchUsingOR = false; if (whereClause.IndexOf(" OR ") > 0) // did they want to do "a=b OR c=d OR..."? searchUsingOR = true; database.AddInParameter(commandWrapper, "@SearchUsingOR", DbType.Boolean, searchUsingOR); database.AddInParameter(commandWrapper, "@Id", DbType.Int32, DBNull.Value); database.AddInParameter(commandWrapper, "@Name", DbType.String, DBNull.Value); database.AddInParameter(commandWrapper, "@Address", DbType.String, DBNull.Value); database.AddInParameter(commandWrapper, "@ClassId", DbType.Int32, DBNull.Value); database.AddInParameter(commandWrapper, "@Birthdate", DbType.Date, DBNull.Value); database.AddInParameter(commandWrapper, "@Gender", DbType.String, DBNull.Value); // replace all instances of 'AND' and 'OR' because we already set searchUsingOR whereClause = whereClause.Replace(" AND ", "|").Replace(" OR ", "|") ; string[] clauses = whereClause.ToLower().Split('|'); // Here's what's going on below: Find a field, then to get the value we // drop the field name from the front, trim spaces, drop the '=' sign, // trim more spaces, and drop any outer single quotes. // Now handles the case when two fields start off the same way - like "Friendly='Yes' AND Friend='john'" char[] equalSign = {'='}; char[] singleQuote = {'\''}; foreach (string clause in clauses) { if (clause.Trim().StartsWith("id ") || clause.Trim().StartsWith("id=")) { database.SetParameterValue(commandWrapper, "@Id", clause.Trim().Remove(0,2).Trim().TrimStart(equalSign).Trim().Trim(singleQuote)); continue; } if (clause.Trim().StartsWith("name ") || clause.Trim().StartsWith("name=")) { database.SetParameterValue(commandWrapper, "@Name", clause.Trim().Remove(0,4).Trim().TrimStart(equalSign).Trim().Trim(singleQuote)); continue; } if (clause.Trim().StartsWith("address ") || clause.Trim().StartsWith("address=")) { database.SetParameterValue(commandWrapper, "@Address", clause.Trim().Remove(0,7).Trim().TrimStart(equalSign).Trim().Trim(singleQuote)); continue; } if (clause.Trim().StartsWith("classid ") || clause.Trim().StartsWith("classid=")) { database.SetParameterValue(commandWrapper, "@ClassId", clause.Trim().Remove(0,7).Trim().TrimStart(equalSign).Trim().Trim(singleQuote)); continue; } if (clause.Trim().StartsWith("birthdate ") || clause.Trim().StartsWith("birthdate=")) { database.SetParameterValue(commandWrapper, "@Birthdate", clause.Trim().Remove(0,9).Trim().TrimStart(equalSign).Trim().Trim(singleQuote)); continue; } if (clause.Trim().StartsWith("gender ") || clause.Trim().StartsWith("gender=")) { database.SetParameterValue(commandWrapper, "@Gender", clause.Trim().Remove(0,6).Trim().TrimStart(equalSign).Trim().Trim(singleQuote)); continue; } throw new ArgumentException("Unable to use this part of the where clause in this version of Find: " + clause); } IDataReader reader = null; //Create Collection TList<Students> rows = new TList<Students>(); try { //Provider Data Requesting Command Event OnDataRequesting(new CommandEventArgs(commandWrapper, "Find", rows)); if (transactionManager != null) { reader = Utility.ExecuteReader(transactionManager, commandWrapper); } else { reader = Utility.ExecuteReader(database, commandWrapper); } Fill(reader, rows, start, pageLength); if(reader.NextResult()) { if(reader.Read()) { count = reader.GetInt32(0); } } //Provider Data Requested Command Event OnDataRequested(new CommandEventArgs(commandWrapper, "Find", rows)); } finally { if (reader != null) reader.Close(); commandWrapper = null; } return rows; }
/// <summary> /// Executes the scalar. /// </summary> /// <param name="transactionManager">The transaction manager.</param> /// <param name="commandType">Type of the command.</param> /// <param name="commandText">The command text.</param> /// <returns></returns> public override object ExecuteScalar(TransactionManager transactionManager, CommandType commandType, string commandText) { Database database = transactionManager.Database; return database.ExecuteScalar(transactionManager.TransactionObject , commandType, commandText); }
/// <summary> /// Lets you efficiently bulk insert many entities to the database. /// </summary> /// <param name="transactionManager">The transaction manager.</param> /// <param name="entities">The entities.</param> /// <remarks> /// After inserting into the datasource, the School.Entities.Students object will be updated /// to refelect any changes made by the datasource. (ie: identity or computed columns) /// </remarks> public override void BulkInsert(TransactionManager transactionManager, TList<School.Entities.Students> entities) { //System.Data.SqlClient.SqlBulkCopy bulkCopy = new System.Data.SqlClient.SqlBulkCopy(this._connectionString, System.Data.SqlClient.SqlBulkCopyOptions.CheckConstraints); //, null); System.Data.SqlClient.SqlBulkCopy bulkCopy = null; if (transactionManager != null && transactionManager.IsOpen) { System.Data.SqlClient.SqlConnection cnx = transactionManager.TransactionObject.Connection as System.Data.SqlClient.SqlConnection; System.Data.SqlClient.SqlTransaction transaction = transactionManager.TransactionObject as System.Data.SqlClient.SqlTransaction; bulkCopy = new System.Data.SqlClient.SqlBulkCopy(cnx, System.Data.SqlClient.SqlBulkCopyOptions.CheckConstraints, transaction); //, null); } else { bulkCopy = new System.Data.SqlClient.SqlBulkCopy(this._connectionString, System.Data.SqlClient.SqlBulkCopyOptions.CheckConstraints); //, null); } bulkCopy.BulkCopyTimeout = 360; bulkCopy.DestinationTableName = "Students"; DataTable dataTable = new DataTable(); DataColumn col0 = dataTable.Columns.Add("Id", typeof(System.Int32)); col0.AllowDBNull = false; DataColumn col1 = dataTable.Columns.Add("Name", typeof(System.String)); col1.AllowDBNull = false; DataColumn col2 = dataTable.Columns.Add("Address", typeof(System.String)); col2.AllowDBNull = false; DataColumn col3 = dataTable.Columns.Add("ClassId", typeof(System.Int32)); col3.AllowDBNull = false; DataColumn col4 = dataTable.Columns.Add("Birthdate", typeof(System.DateTime)); col4.AllowDBNull = false; DataColumn col5 = dataTable.Columns.Add("Gender", typeof(System.String)); col5.AllowDBNull = false; bulkCopy.ColumnMappings.Add("Id", "Id"); bulkCopy.ColumnMappings.Add("Name", "Name"); bulkCopy.ColumnMappings.Add("Address", "Address"); bulkCopy.ColumnMappings.Add("ClassId", "ClassId"); bulkCopy.ColumnMappings.Add("Birthdate", "Birthdate"); bulkCopy.ColumnMappings.Add("Gender", "Gender"); foreach(School.Entities.Students entity in entities) { if (entity.EntityState != EntityState.Added) continue; DataRow row = dataTable.NewRow(); row["Id"] = entity.Id; row["Name"] = entity.Name; row["Address"] = entity.Address; row["ClassId"] = entity.ClassId; row["Birthdate"] = entity.Birthdate; row["Gender"] = entity.Gender; dataTable.Rows.Add(row); } // send the data to the server bulkCopy.WriteToServer(dataTable); // update back the state foreach(School.Entities.Students entity in entities) { if (entity.EntityState != EntityState.Added) continue; entity.AcceptChanges(); } }
/// <summary> /// Executes the scalar. /// </summary> /// <param name="transactionManager">The transaction manager.</param> /// <param name="commandWrapper">The command wrapper.</param> /// <returns></returns> public override object ExecuteScalar(TransactionManager transactionManager, DbCommand commandWrapper) { Database database = transactionManager.Database; return database.ExecuteScalar(commandWrapper, transactionManager.TransactionObject); }
/// <summary> /// Executes the scalar. /// </summary> /// <param name="transactionManager">The transaction manager.</param> /// <param name="storedProcedureName">Name of the stored procedure.</param> /// <param name="parameterValues">The parameter values.</param> /// <returns></returns> public override object ExecuteScalar(TransactionManager transactionManager, string storedProcedureName, params object[] parameterValues) { Database database = transactionManager.Database; return database.ExecuteScalar(transactionManager.TransactionObject, storedProcedureName, parameterValues); }
/// <summary> /// Executes the non query. /// </summary> /// <param name="transactionManager">The transaction manager.</param> /// <param name="commandType">Type of the command.</param> /// <param name="commandText">The command text.</param> /// <returns></returns> public override int ExecuteNonQuery(TransactionManager transactionManager, CommandType commandType, string commandText) { Database database = transactionManager.Database; return database.ExecuteNonQuery(transactionManager.TransactionObject , commandType, commandText); }
/// <summary> /// Executes the non query. /// </summary> /// <param name="transactionManager">The transaction manager.</param> /// <param name="commandWrapper">The command wrapper.</param> public override void ExecuteNonQuery(TransactionManager transactionManager, DbCommand commandWrapper) { SqlDatabase database = new SqlDatabase(this._connectionString); database.ExecuteNonQuery(commandWrapper, transactionManager.TransactionObject); }
/// <summary> /// Executes the non query. /// </summary> /// <param name="transactionManager">The transaction manager.</param> /// <param name="storedProcedureName">Name of the stored procedure.</param> /// <param name="parameterValues">The parameter values.</param> /// <returns></returns> public override int ExecuteNonQuery(TransactionManager transactionManager, string storedProcedureName, params object[] parameterValues) { SqlDatabase database = new SqlDatabase(this._connectionString); return database.ExecuteNonQuery(transactionManager.TransactionObject, storedProcedureName, parameterValues); }