/// <summary> /// Función que carga la relacion Category desde la base de datos /// </summary> /// <param name="serviceCategory">Padre: ServiceCategoryEntity</param> /// <exception cref="ArgumentNullException"> /// Si <paramref name="serviceCategory"/> no es un <c>ServiceCategoryEntity</c>. /// </exception> public void LoadRelationCategory(ServiceCategoryEntity serviceCategory, Dictionary <string, IEntity> scope) { if (serviceCategory == null) { throw new ArgumentException("The argument can't be null"); } bool closeConnection = false; try { // Crea una nueva conexión si es necesario if (dbConnection == null || dbConnection.State.CompareTo(ConnectionState.Closed) == 0) { closeConnection = true; dbConnection = dataAccess.GetNewConnection(); dbConnection.Open(); } // Crea un nuevo command string cmdText = "SELECT idCategory FROM [ServiceCategory] WHERE idServiceCategory = @idServiceCategory"; SqlCeCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction); SqlCeParameter parameter = dataAccess.GetNewDataParameter("@idServiceCategory", DbType.Int32); // Establece los valores a los parametros del command parameter.Value = serviceCategory.Id; sqlCommand.Parameters.Add(parameter); // Execute commands object idRelation = sqlCommand.ExecuteScalar(); if (idRelation != null && ((int)idRelation) > 0) { // Create data access objects and set connection objects CategoryDataAccess categoryDataAccess = new CategoryDataAccess(); categoryDataAccess.SetConnectionObjects(dbConnection, dbTransaction); // Carga los objetos relacionados serviceCategory.Category = categoryDataAccess.Load(((int)idRelation), true, scope); } } catch (DbException dbException) { // Relanza una excepcion personalizada throw new UtnEmallDataAccessException(dbException.Message, dbException); } finally { // Cierra la conexión si fue inicializada if (closeConnection) { dbConnection.Close(); } } }
/// <summary> /// Function to Load the relation Category from database. /// </summary> /// <param name="serviceCategory">ServiceCategoryEntity parent</param> /// <exception cref="ArgumentNullException"> /// if <paramref name="serviceCategory"/> is not a <c>ServiceCategoryEntity</c>. /// </exception> public void LoadRelationCategory(ServiceCategoryEntity serviceCategory, Dictionary <string, IEntity> scope) { if (serviceCategory == null) { throw new ArgumentException("The argument can't be null"); } bool closeConnection = false; try { // Create a new connection if needed if (dbConnection == null || dbConnection.State.CompareTo(ConnectionState.Closed) == 0) { closeConnection = true; dbConnection = dataAccess.GetNewConnection(); dbConnection.Open(); } // Create a command string cmdText = "SELECT idCategory FROM [ServiceCategory] WHERE idServiceCategory = @idServiceCategory"; IDbCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction); IDbDataParameter parameter = dataAccess.GetNewDataParameter("@idServiceCategory", DbType.Int32); // Set command parameters values parameter.Value = serviceCategory.Id; sqlCommand.Parameters.Add(parameter); // Execute commands object idRelation = sqlCommand.ExecuteScalar(); if (idRelation != null && ((int)idRelation) > 0) { // Create data access objects and set connection objects CategoryDataAccess categoryDataAccess = new CategoryDataAccess(); categoryDataAccess.SetConnectionObjects(dbConnection, dbTransaction); // Load related object serviceCategory.Category = categoryDataAccess.Load(((int)idRelation), true, scope); } } catch (DbException dbException) { // Catch and rethrow as custom exception throw new UtnEmallDataAccessException(dbException.Message, dbException); } finally { // Close connection if initiated by me if (closeConnection) { dbConnection.Close(); } } }
private void FillSaveParameters(ServiceCategoryEntity serviceCategory, IDbCommand sqlCommand) { IDbDataParameter parameter; parameter = dataAccess.GetNewDataParameter("@idService", DbType.Int32); parameter.Value = serviceCategory.IdService; sqlCommand.Parameters.Add(parameter); parameter = dataAccess.GetNewDataParameter("@idCategory", DbType.Int32); parameter.Value = serviceCategory.IdCategory; sqlCommand.Parameters.Add(parameter); }
/// <summary> /// Retorna las categorias seleccionadas para el servicio. /// </summary> /// <returns>Categorias del servicio</returns> public Collection <ServiceCategoryEntity> SaveServiceCategories() { serviceEntity.ServiceCategory.Clear(); CategoryEntity category; Collection <ServiceCategoryEntity> list = new Collection <ServiceCategoryEntity>(); foreach (TreeNode node in treeView.CheckedNodes) { if (storeCategories.TryGetValue(node.Text, out category)) { if (category.Name == node.Text) { ServiceCategoryEntity serviceCategory = new ServiceCategoryEntity(); serviceCategory.Category = category; list.Add(serviceCategory); } } } return(list); }
/// <summary> /// Actualiza la base de datos para reflejar el estado actual de la lista. /// </summary> /// <param name="collectionDataAccess">El IDataAccess de la relación</param> /// <param name="parent">El objeto padre</param> /// <param name="collection">una colección de items</param> /// <param name="isNewParent">Si el padre es un objeto nuevo</param> /// <param name="scope">Estructura de datos interna para evitar problemas de referencia circular</param> /// <exception cref="UtnEmallDataAccessException"> /// Si una DbException ocurre cuando se accede a la base de datos /// </exception> private void SaveServiceCategoryCollection(ServiceCategoryDataAccess collectionDataAccess, ServiceEntity parent, Collection <ServiceCategoryEntity> collection, bool isNewParent, Dictionary <string, IEntity> scope) { if (collection == null) { return; } // Establece los objetos de conexión collectionDataAccess.SetConnectionObjects(dbConnection, dbTransaction); // Establece la relación padre/hijo for (int i = 0; i < collection.Count; i++) { bool changed = collection[i].Changed; collection[i].Service = parent; collection[i].Changed = changed; } // Si el padre es nuevo guarda todos los hijos, sino controla las diferencias con la base de datos. if (isNewParent) { for (int i = 0; i < collection.Count; i++) { collectionDataAccess.Save(collection[i], scope); } } else { // Controla los hijos que ya no son parte de la relación string idList = "0"; if (collection.Count > 0) { idList = "" + collection[0].Id; } for (int i = 1; i < collection.Count; i++) { idList += ", " + collection[i].Id; } // Retorna los ids que ya no existe en la colección actual string command = "SELECT idServiceCategory FROM [ServiceCategory] WHERE idService = @idService AND idServiceCategory NOT IN (" + idList + ")"; SqlCeCommand sqlCommand = dataAccess.GetNewCommand(command, dbConnection, dbTransaction); SqlCeParameter sqlParameterId = dataAccess.GetNewDataParameter("@idService", DbType.Int32); sqlParameterId.Value = parent.Id; sqlCommand.Parameters.Add(sqlParameterId); IDataReader reader = sqlCommand.ExecuteReader(); Collection <ServiceCategoryEntity> objectsToDelete = new Collection <ServiceCategoryEntity>(); // Inserta los id en una lista List <int> listId = new List <int>(); while (reader.Read()) { listId.Add(reader.GetInt32(0)); } reader.Close(); // Carga los items a ser eliminados foreach (int id in listId) { ServiceCategoryEntity entityToDelete = collectionDataAccess.Load(id, scope); objectsToDelete.Add(entityToDelete); } // Esto se realiza porque el reader debe ser cerrado despues de eliminar las entidades for (int i = 0; i < objectsToDelete.Count; i++) { collectionDataAccess.Delete(objectsToDelete[i], scope); } System.DateTime timestamp; // Controla todas las propiedades de los items de la colección // para verificar si alguno cambio for (int i = 0; i < collection.Count; i++) { ServiceCategoryEntity item = collection[i]; if (!item.Changed && !item.IsNew) { // Crea el command string sql = "SELECT timestamp FROM [ServiceCategory] WHERE idServiceCategory = @idServiceCategory"; SqlCeCommand sqlCommandTimestamp = dataAccess.GetNewCommand(sql, dbConnection, dbTransaction); // Establece los datos a los parametros del command SqlCeParameter sqlParameterIdPreference = dataAccess.GetNewDataParameter("@idServiceCategory", DbType.Int32); sqlParameterIdPreference.Value = item.Id; sqlCommandTimestamp.Parameters.Add(sqlParameterIdPreference); timestamp = ((System.DateTime)sqlCommandTimestamp.ExecuteScalar()); if (item.Timestamp != timestamp) { item.Changed = true; } } // Guarda el item si cambio o es nuevo if (item.Changed || item.IsNew) { collectionDataAccess.Save(item); } } } }
/// <summary> /// Carga el contenido del formulario en un objeto de entidad /// </summary> private void Load() { if (mode == EditionMode.Add) { service = new ServiceEntity(); } service.Name = TxtName.Text.Trim(); service.Description = TxtDescription.Text.Trim(); service.StartDate = StartDate.Date; service.StopDate = StopDate.Date; if (storeCombo.SelectedIndex == 0) { service.Store = null; } else { service.Store = stores[(string)storeCombo.SelectedItem]; } System.Collections.Generic.List <ServiceCategoryEntity> toRemove = new System.Collections.Generic.List <ServiceCategoryEntity>(); // Si las categorías fueron modificadas if (this.categoriesLoaded) { // se recorren todas las categorías de servicio foreach (ServiceCategoryEntity serviceCategory in service.ServiceCategory) { bool exists = false; foreach (CategoryEntity category in categoryWindow.Selected) { // No se elimina una categoría ya asignada if (serviceCategory.Category.Name == category.Name) { exists = true; break; } } if (!exists) { toRemove.Add(serviceCategory); } } foreach (ServiceCategoryEntity serviceCategory in toRemove) { service.ServiceCategory.Remove(serviceCategory); } // recorremos todas las categorías foreach (CategoryEntity category in categoryWindow.Selected) { bool exists = false; foreach (ServiceCategoryEntity serviceCategory in service.ServiceCategory) { if (serviceCategory.Category.Name == category.Name) { exists = true; break; } } if (!exists) { ServiceCategoryEntity newServiceCategory = new ServiceCategoryEntity(); newServiceCategory.Category = category; service.ServiceCategory.Add(newServiceCategory); } } } }
/// <summary> /// Function to load a ServiceCategoryEntity from database. /// </summary> /// <param name="id">The ID of the record to load</param> /// <param name="loadRelation">if is true load the relation</param> /// <param name="scope">Internal structure used to avoid circular reference locks, must be provided if calling from other data access object</param> /// <returns>The entity instance</returns> /// <exception cref="UtnEmallDataAccessException"> /// If a DbException occurs while accessing the database. /// </exception> public ServiceCategoryEntity Load(int id, bool loadRelation, Dictionary <string, IEntity> scope) { // Build a key for internal scope object string scopeKey = id.ToString(NumberFormatInfo.InvariantInfo) + "ServiceCategory"; if (scope != null) { // If scope contains the object it was already loaded, // return it to avoid circular references if (scope.ContainsKey(scopeKey)) { return((ServiceCategoryEntity)scope[scopeKey]); } } else { // If there isn't a current scope create one scope = new Dictionary <string, IEntity>(); } ServiceCategoryEntity serviceCategory = null; // Check if the entity was already loaded by current data access object // and return it if that is the case if (inMemoryEntities.ContainsKey(id)) { serviceCategory = inMemoryEntities[id]; // Add current object to current load scope scope.Add(scopeKey, serviceCategory); } else { bool closeConnection = false; try { // Open a new connection if it isn't on a transaction if (dbConnection == null || dbConnection.State.CompareTo(ConnectionState.Closed) == 0) { closeConnection = true; dbConnection = dataAccess.GetNewConnection(); dbConnection.Open(); } string cmdText = "SELECT idServiceCategory, idService, idCategory, timestamp FROM [ServiceCategory] WHERE idServiceCategory = @idServiceCategory"; // Create the command IDbCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction); // Create the Id parameter for the query IDbDataParameter parameter = dataAccess.GetNewDataParameter("@idServiceCategory", DbType.Int32); parameter.Value = id; sqlCommand.Parameters.Add(parameter); // Use a DataReader to get data from db IDataReader reader = sqlCommand.ExecuteReader(); serviceCategory = new ServiceCategoryEntity(); if (reader.Read()) { // Load fields of entity serviceCategory.Id = reader.GetInt32(0); serviceCategory.IdService = reader.GetInt32(1); serviceCategory.IdCategory = reader.GetInt32(2); // Add current object to the scope scope.Add(scopeKey, serviceCategory); // Add current object to cache of loaded entities inMemoryEntities.Add(serviceCategory.Id, serviceCategory); // Read the timestamp and set new and changed properties serviceCategory.Timestamp = reader.GetDateTime(3); serviceCategory.IsNew = false; serviceCategory.Changed = false; // Close the reader reader.Close(); // Load related objects if required if (loadRelation) { LoadRelationCategory(serviceCategory, scope); } } else { reader.Close(); } } catch (DbException dbException) { // Catch DBException and rethrow as custom exception throw new UtnEmallDataAccessException(dbException.Message, dbException); } finally { // Close connection if it was opened by ourself if (closeConnection) { dbConnection.Close(); } } } // Return the loaded entity return(serviceCategory); }
/// <summary> /// Function to Delete a ServiceCategoryEntity from database. /// </summary> /// <param name="serviceCategory">ServiceCategoryEntity to delete</param> /// <param name="scope">Internal structure to avoid circular reference locks. Must provide an instance while calling from other data access object.</param> /// <exception cref="ArgumentNullException"> /// If <paramref name="serviceCategory"/> is not a <c>ServiceCategoryEntity</c>. /// </exception> /// <exception cref="UtnEmallDataAccessException"> /// If an DbException occurs in the try block while accessing the database. /// </exception> public void Delete(ServiceCategoryEntity serviceCategory, Dictionary <string, IEntity> scope) { if (serviceCategory == null) { throw new ArgumentException("The argument can't be null"); } try { // Open connection and initialize a transaction if needed if (!isGlobalTransaction) { dbConnection = dataAccess.GetNewConnection(); dbConnection.Open(); dbTransaction = dbConnection.BeginTransaction(); } // Reload the entity to ensure deletion of older data serviceCategory = this.Load(serviceCategory.Id, true); if (serviceCategory == null) { throw new UtnEmallDataAccessException("Error retrieving data while trying to delete."); } // Create a command for delete string cmdText = "DeleteServiceCategory"; IDbCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction); sqlCommand.CommandType = CommandType.StoredProcedure; // Add values to parameters IDbDataParameter parameterID = dataAccess.GetNewDataParameter("@idServiceCategory", DbType.Int32); parameterID.Value = serviceCategory.Id; sqlCommand.Parameters.Add(parameterID); // Execute the command sqlCommand.ExecuteNonQuery(); // Delete related objects // Commit transaction if is mine if (!isGlobalTransaction) { dbTransaction.Commit(); } // Remove entity from loaded objects inMemoryEntities.Remove(serviceCategory.Id); // Remove entity from current internal scope if (scope != null) { string scopeKey = serviceCategory.Id.ToString(NumberFormatInfo.InvariantInfo) + "ServiceCategory"; scope.Remove(scopeKey); } } catch (DbException dbException) { // Rollback transaction if (!isGlobalTransaction) { dbTransaction.Rollback(); } // Rethrow as custom exception throw new UtnEmallDataAccessException(dbException.Message, dbException); } finally { // Close connection if it was initiated by this instance if (!isGlobalTransaction) { dbConnection.Close(); dbConnection = null; dbTransaction = null; } } }
/// <summary> /// Function to Delete a ServiceCategoryEntity from database. /// </summary> /// <param name="serviceCategory">ServiceCategoryEntity to delete</param> /// <exception cref="ArgumentNullException"> /// If <paramref name="serviceCategory"/> is not a <c>ServiceCategoryEntity</c>. /// </exception> /// <exception cref="UtnEmallDataAccessException"> /// If an DbException occurs in the try block while accessing the database. /// </exception> public void Delete(ServiceCategoryEntity serviceCategory) { Delete(serviceCategory, null); }
/// <summary> /// Function to Save a ServiceCategoryEntity in the database. /// </summary> /// <param name="serviceCategory">ServiceCategoryEntity to save</param> /// <param name="scope">Interna structure to avoid circular reference locks. Provide an instance when calling from other data access object.</param> /// <exception cref="ArgumentNullException"> /// If <paramref name="serviceCategory"/> is not a <c>ServiceCategoryEntity</c>. /// </exception> /// <exception cref="UtnEmallDataAccessException"> /// If an DbException occurs in the try block while accessing the database. /// </exception> public void Save(ServiceCategoryEntity serviceCategory, Dictionary <string, IEntity> scope) { if (serviceCategory == null) { throw new ArgumentException("The argument can't be null"); } // Create a unique key to identify the object in the internal scope string scopeKey = serviceCategory.Id.ToString(NumberFormatInfo.InvariantInfo) + "ServiceCategory"; if (scope != null) { // If it's on the scope return it, don't save again if (scope.ContainsKey(scopeKey)) { return; } } else { // Create a new scope if it's not provided scope = new Dictionary <string, IEntity>(); } try { // Open a DbConnection and a new transaction if it isn't on a higher level one if (!isGlobalTransaction) { dbConnection = dataAccess.GetNewConnection(); dbConnection.Open(); dbTransaction = dbConnection.BeginTransaction(); } string commandName = ""; bool isUpdate = false; // Check if it is an insert or update command if (serviceCategory.IsNew || !DataAccessConnection.ExistsEntity(serviceCategory.Id, "ServiceCategory", "idServiceCategory", dbConnection, dbTransaction)) { commandName = "SaveServiceCategory"; } else { isUpdate = true; commandName = "UpdateServiceCategory"; } // Create a db command IDbCommand sqlCommand = dataAccess.GetNewCommand(commandName, dbConnection, dbTransaction); sqlCommand.CommandType = CommandType.StoredProcedure; // Add parameters values to current command IDbDataParameter parameter; if (isUpdate) { parameter = dataAccess.GetNewDataParameter("@idServiceCategory", DbType.Int32); parameter.Value = serviceCategory.Id; sqlCommand.Parameters.Add(parameter); } FillSaveParameters(serviceCategory, sqlCommand); // Execute the command if (isUpdate) { sqlCommand.ExecuteNonQuery(); } else { IDbDataParameter parameterIdOutput = dataAccess.GetNewDataParameter("@idServiceCategory", DbType.Int32); parameterIdOutput.Direction = ParameterDirection.ReturnValue; sqlCommand.Parameters.Add(parameterIdOutput); sqlCommand.ExecuteNonQuery(); serviceCategory.Id = Convert.ToInt32(parameterIdOutput.Value, NumberFormatInfo.InvariantInfo); } scopeKey = serviceCategory.Id.ToString(NumberFormatInfo.InvariantInfo) + "ServiceCategory"; // Add entity to current internal scope scope.Add(scopeKey, serviceCategory); // Save collections of related objects to current entity // Save objects related to current entity // Update // Close transaction if initiated by me if (!isGlobalTransaction) { dbTransaction.Commit(); } // Update new and changed flags serviceCategory.IsNew = false; serviceCategory.Changed = false; } catch (DbException dbException) { // Rollback transaction if (!isGlobalTransaction) { dbTransaction.Rollback(); } // Rethrow as custom exception throw new UtnEmallDataAccessException(dbException.Message, dbException); } finally { // Close connection if initiated by me if (!isGlobalTransaction) { dbConnection.Close(); dbConnection = null; dbTransaction = null; } } }
/// <summary> /// Function to Save a ServiceCategoryEntity in the database. /// </summary> /// <param name="serviceCategory">ServiceCategoryEntity to save</param> /// <exception cref="ArgumentNullException"> /// if <paramref name="serviceCategory"/> is not a <c>ServiceCategoryEntity</c>. /// </exception> /// <exception cref="UtnEmallDataAccessException"> /// If an DbException occurs in the try block while accessing the database. /// </exception> public void Save(ServiceCategoryEntity serviceCategory) { Save(serviceCategory, null); }
/// <summary> /// Función para cargar un ServiceCategoryEntity desde la base de datos. /// </summary> /// <param name="id">El id del registro a cargar</param> /// <param name="loadRelation">Si es true carga las relaciones</param> /// <param name="scope">Estructura interna usada para evitar la referencia circular, debe ser proveida si es llamada desde otro data access</param> /// <returns>La instancia de la entidad</returns> /// <exception cref="UtnEmallDataAccessException"> /// Si una DbException ocurre mientras se accede a la base de datos /// </exception> public ServiceCategoryEntity Load(int id, bool loadRelation, Dictionary <string, IEntity> scope) { // Crea una clave para el objeto de scope interno string scopeKey = id.ToString(NumberFormatInfo.InvariantInfo) + "ServiceCategory"; if (scope != null) { // Si el scope contiene el objeto, este ya fue cargado // retorna el objeto situado en el scope para evitar referencias circulares if (scope.ContainsKey(scopeKey)) { return((ServiceCategoryEntity)scope[scopeKey]); } } else { // Si no existe un scope, crear uno scope = new Dictionary <string, IEntity>(); } ServiceCategoryEntity serviceCategory = null; // Chequear si la entidad fue ya cargada por el data access actual // y retornar si fue ya cargada if (inMemoryEntities.ContainsKey(id)) { serviceCategory = inMemoryEntities[id]; // Agregar el objeto actual al scope scope.Add(scopeKey, serviceCategory); } else { bool closeConnection = false; try { // Abrir una nueva conexión si no es una transaccion if (dbConnection == null || dbConnection.State.CompareTo(ConnectionState.Closed) == 0) { closeConnection = true; dbConnection = dataAccess.GetNewConnection(); dbConnection.Open(); } string cmdText = "SELECT idServiceCategory, idService, idCategory, timestamp FROM [ServiceCategory] WHERE idServiceCategory = @idServiceCategory"; // Crea el command SqlCeCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction); // Crear el parametro id para la consulta SqlCeParameter parameter = dataAccess.GetNewDataParameter("@idServiceCategory", DbType.Int32); parameter.Value = id; sqlCommand.Parameters.Add(parameter); // Usar el datareader para cargar desde la base de datos IDataReader reader = sqlCommand.ExecuteReader(); serviceCategory = new ServiceCategoryEntity(); if (reader.Read()) { // Cargar las filas de la entidad serviceCategory.Id = reader.GetInt32(0); serviceCategory.IdService = reader.GetInt32(1); serviceCategory.IdCategory = reader.GetInt32(2); // Agregar el objeto actual al scope scope.Add(scopeKey, serviceCategory); // Agregar el objeto a la cahce de entidades cargadas inMemoryEntities.Add(serviceCategory.Id, serviceCategory); // Lee el timestamp y establece las propiedades nuevo y cambiado serviceCategory.Timestamp = reader.GetDateTime(3); serviceCategory.IsNew = false; serviceCategory.Changed = false; // Cerrar el Reader reader.Close(); // Carga los objetos relacionadoss if required if (loadRelation) { LoadRelationCategory(serviceCategory, scope); } } else { reader.Close(); } } catch (DbException dbException) { // Relanza la excepcion como una excepcion personalizada throw new UtnEmallDataAccessException(dbException.Message, dbException); } finally { // Cierra la conexión si fue creada dentro de la Función if (closeConnection) { dbConnection.Close(); } } } // Retorna la entidad cargada return(serviceCategory); }
/// <summary> /// Función que elimina un ServiceCategoryEntity de la base de datos. /// </summary> /// <param name="serviceCategory">ServiceCategoryEntity a eliminar</param> /// <param name="scope">Estructura interna para evitar problemas de referencia circular.</param> /// <exception cref="ArgumentNullException"> /// Si <paramref name="serviceCategory"/> no es un <c>ServiceCategoryEntity</c>. /// </exception> /// <exception cref="UtnEmallDataAccessException"> /// Si una DbException ocurre cuando se accede a la base de datos /// </exception> public void Delete(ServiceCategoryEntity serviceCategory, Dictionary <string, IEntity> scope) { if (serviceCategory == null) { throw new ArgumentException("The argument can't be null"); } try { // Abrir una nueva conexión e inicializar una transacción si es necesario if (!isGlobalTransaction) { dbConnection = dataAccess.GetNewConnection(); dbConnection.Open(); dbTransaction = dbConnection.BeginTransaction(); } // Carga la entidad para garantizar eliminar todos los datos antiguos. serviceCategory = this.Load(serviceCategory.Id, true); if (serviceCategory == null) { throw new UtnEmallDataAccessException("Error al recuperar datos al intentar eliminar."); } // Crea un nuevo command para eliminar string cmdText = "DELETE FROM [ServiceCategory] WHERE idServiceCategory = @idServiceCategory"; SqlCeCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction); // Agrega los valores de los parametros SqlCeParameter parameterID = dataAccess.GetNewDataParameter("@idServiceCategory", DbType.Int32); parameterID.Value = serviceCategory.Id; sqlCommand.Parameters.Add(parameterID); // Ejecuta el comando sqlCommand.ExecuteNonQuery(); // Elimina los objetos relacionados // Confirma la transacción si se inicio dentro de la función if (!isGlobalTransaction) { dbTransaction.Commit(); } // Eliminamos la entidad de la lista de entidades cargadas en memoria inMemoryEntities.Remove(serviceCategory.Id); // Eliminamos la entidad del scope if (scope != null) { string scopeKey = serviceCategory.Id.ToString(NumberFormatInfo.InvariantInfo) + "ServiceCategory"; scope.Remove(scopeKey); } } catch (DbException dbException) { // Anula la transaccion if (!isGlobalTransaction) { dbTransaction.Rollback(); } // Relanza una excepcion personalizada throw new UtnEmallDataAccessException(dbException.Message, dbException); } finally { // Cierra la conexión si fue abierta dentro de la Función if (!isGlobalTransaction) { dbConnection.Close(); dbConnection = null; dbTransaction = null; } } }
/// <summary> /// Función que guarda un ServiceCategoryEntity en la base de datos. /// </summary> /// <param name="serviceCategory">ServiceCategoryEntity a guardar</param> /// <param name="scope">Estructura interna para evitar problemas con referencias circulares</param> /// <exception cref="ArgumentNullException"> /// Si <paramref name="serviceCategory"/> no es un <c>ServiceCategoryEntity</c>. /// </exception> /// <exception cref="UtnEmallDataAccessException"> /// Si una DbException ocurre cuando se accede a la base de datos /// </exception> public void Save(ServiceCategoryEntity serviceCategory, Dictionary <string, IEntity> scope) { if (serviceCategory == null) { throw new ArgumentException("The argument can't be null"); } // Crear una clave unica para identificar el objeto dentro del scope interno string scopeKey = serviceCategory.Id.ToString(NumberFormatInfo.InvariantInfo) + "ServiceCategory"; if (scope != null) { // Si se encuentra dentro del scope lo retornamos if (scope.ContainsKey(scopeKey)) { return; } } else { // Crea un nuevo scope si este no fue enviado scope = new Dictionary <string, IEntity>(); } try { // Crea una nueva conexion y una nueva transaccion si no hay una a nivel superior if (!isGlobalTransaction) { dbConnection = dataAccess.GetNewConnection(); dbConnection.Open(); dbTransaction = dbConnection.BeginTransaction(); } string commandName = ""; bool isUpdate = false; // Verifica si se debe hacer una actualización o una inserción if (serviceCategory.IsNew || !DataAccessConnection.ExistsEntity(serviceCategory.Id, "ServiceCategory", "idServiceCategory", dbConnection, dbTransaction)) { commandName = "INSERT INTO [ServiceCategory] (idServiceCategory, IDSERVICE, IDCATEGORY, [TIMESTAMP] ) VALUES( @idServiceCategory, @idService,@idCategory, GETDATE()); "; } else { isUpdate = true; commandName = "UPDATE [ServiceCategory] SET idService = @idService, idCategory = @idCategory , timestamp=GETDATE() WHERE idServiceCategory = @idServiceCategory"; } // Se crea un command SqlCeCommand sqlCommand = dataAccess.GetNewCommand(commandName, dbConnection, dbTransaction); // Agregar los parametros del command . SqlCeParameter parameter; if (!isUpdate && serviceCategory.Id == 0) { serviceCategory.Id = DataAccessConnection.GetNextId("idServiceCategory", "ServiceCategory", dbConnection, dbTransaction); } parameter = dataAccess.GetNewDataParameter("@idServiceCategory", DbType.Int32); parameter.Value = serviceCategory.Id; sqlCommand.Parameters.Add(parameter); FillSaveParameters(serviceCategory, sqlCommand); // Ejecutar el command sqlCommand.ExecuteNonQuery(); scopeKey = serviceCategory.Id.ToString(NumberFormatInfo.InvariantInfo) + "ServiceCategory"; // Agregar la entidad al scope actual scope.Add(scopeKey, serviceCategory); // Guarda las colecciones de objetos relacionados. // Guardar objetos relacionados con la entidad actual // Actualizar // Cierra la conexión si fue abierta en la función if (!isGlobalTransaction) { dbTransaction.Commit(); } // Actualizar los campos new y changed serviceCategory.IsNew = false; serviceCategory.Changed = false; } catch (DbException dbException) { // Anula la transaccion if (!isGlobalTransaction) { dbTransaction.Rollback(); } // Relanza una excepcion personalizada throw new UtnEmallDataAccessException(dbException.Message, dbException); } finally { // Cierra la conexión si fue inicializada if (!isGlobalTransaction) { dbConnection.Close(); dbConnection = null; dbTransaction = null; } } }