/// <summary> /// Función que carga la relacion Category desde la base de datos /// </summary> /// <param name="storeCategory">Padre: StoreCategoryEntity</param> /// <exception cref="ArgumentNullException"> /// Si <paramref name="storeCategory"/> no es un <c>StoreCategoryEntity</c>. /// </exception> public void LoadRelationCategory(StoreCategoryEntity storeCategory, Dictionary <string, IEntity> scope) { if (storeCategory == 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 [StoreCategory] WHERE idStoreCategory = @idStoreCategory"; SqlCeCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction); SqlCeParameter parameter = dataAccess.GetNewDataParameter("@idStoreCategory", DbType.Int32); // Establece los valores a los parametros del command parameter.Value = storeCategory.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 storeCategory.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="storeCategory">StoreCategoryEntity parent</param> /// <exception cref="ArgumentNullException"> /// if <paramref name="storeCategory"/> is not a <c>StoreCategoryEntity</c>. /// </exception> public void LoadRelationCategory(StoreCategoryEntity storeCategory, Dictionary <string, IEntity> scope) { if (storeCategory == 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 [StoreCategory] WHERE idStoreCategory = @idStoreCategory"; IDbCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction); IDbDataParameter parameter = dataAccess.GetNewDataParameter("@idStoreCategory", DbType.Int32); // Set command parameters values parameter.Value = storeCategory.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 storeCategory.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(StoreCategoryEntity storeCategory, IDbCommand sqlCommand) { IDbDataParameter parameter; parameter = dataAccess.GetNewDataParameter("@idCategory", DbType.Int32); parameter.Value = storeCategory.IdCategory; sqlCommand.Parameters.Add(parameter); parameter = dataAccess.GetNewDataParameter("@idStore", DbType.Int32); parameter.Value = storeCategory.IdStore; sqlCommand.Parameters.Add(parameter); }
private static bool ValidateStoreCategory(Collection <StoreCategoryEntity> StoreCategory) { bool result = true; for (int i = 0; i < StoreCategory.Count; i++) { StoreCategoryEntity item = StoreCategory[i]; if (item.Category == null) { item.Errors.Add(new Error("Category", "Category", "La categoría no puede estar vacía")); result = false; } } return(result); }
/// <summary> /// Retorna las categorias seleccionadas para la tienda. /// </summary> /// <returns>Categorias de la tienda.</returns> public Collection <StoreCategoryEntity> SaveStoreCategories() { storeEntity.StoreCategory.Clear(); CategoryEntity category; Collection <StoreCategoryEntity> list = new Collection <StoreCategoryEntity>(); foreach (TreeNode node in treeView.CheckedNodes) { if (categories.TryGetValue(node.Text, out category)) { StoreCategoryEntity storeCategory = new StoreCategoryEntity(); storeCategory.Category = category; list.Add(storeCategory); } } return(list); }
/// <summary> /// Function to load a StoreCategoryEntity 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 StoreCategoryEntity Load(int id, bool loadRelation, Dictionary <string, IEntity> scope) { // Build a key for internal scope object string scopeKey = id.ToString(NumberFormatInfo.InvariantInfo) + "StoreCategory"; if (scope != null) { // If scope contains the object it was already loaded, // return it to avoid circular references if (scope.ContainsKey(scopeKey)) { return((StoreCategoryEntity)scope[scopeKey]); } } else { // If there isn't a current scope create one scope = new Dictionary <string, IEntity>(); } StoreCategoryEntity storeCategory = 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)) { storeCategory = inMemoryEntities[id]; // Add current object to current load scope scope.Add(scopeKey, storeCategory); } 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 idStoreCategory, idCategory, idStore, timestamp FROM [StoreCategory] WHERE idStoreCategory = @idStoreCategory"; // Create the command IDbCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction); // Create the Id parameter for the query IDbDataParameter parameter = dataAccess.GetNewDataParameter("@idStoreCategory", DbType.Int32); parameter.Value = id; sqlCommand.Parameters.Add(parameter); // Use a DataReader to get data from db IDataReader reader = sqlCommand.ExecuteReader(); storeCategory = new StoreCategoryEntity(); if (reader.Read()) { // Load fields of entity storeCategory.Id = reader.GetInt32(0); storeCategory.IdCategory = reader.GetInt32(1); storeCategory.IdStore = reader.GetInt32(2); // Add current object to the scope scope.Add(scopeKey, storeCategory); // Add current object to cache of loaded entities inMemoryEntities.Add(storeCategory.Id, storeCategory); // Read the timestamp and set new and changed properties storeCategory.Timestamp = reader.GetDateTime(3); storeCategory.IsNew = false; storeCategory.Changed = false; // Close the reader reader.Close(); // Load related objects if required if (loadRelation) { LoadRelationCategory(storeCategory, 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(storeCategory); }
/// <summary> /// Function to Delete a StoreCategoryEntity from database. /// </summary> /// <param name="storeCategory">StoreCategoryEntity 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="storeCategory"/> is not a <c>StoreCategoryEntity</c>. /// </exception> /// <exception cref="UtnEmallDataAccessException"> /// If an DbException occurs in the try block while accessing the database. /// </exception> public void Delete(StoreCategoryEntity storeCategory, Dictionary <string, IEntity> scope) { if (storeCategory == 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 storeCategory = this.Load(storeCategory.Id, true); if (storeCategory == null) { throw new UtnEmallDataAccessException("Error retrieving data while trying to delete."); } // Create a command for delete string cmdText = "DeleteStoreCategory"; IDbCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction); sqlCommand.CommandType = CommandType.StoredProcedure; // Add values to parameters IDbDataParameter parameterID = dataAccess.GetNewDataParameter("@idStoreCategory", DbType.Int32); parameterID.Value = storeCategory.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(storeCategory.Id); // Remove entity from current internal scope if (scope != null) { string scopeKey = storeCategory.Id.ToString(NumberFormatInfo.InvariantInfo) + "StoreCategory"; 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 StoreCategoryEntity from database. /// </summary> /// <param name="storeCategory">StoreCategoryEntity to delete</param> /// <exception cref="ArgumentNullException"> /// If <paramref name="storeCategory"/> is not a <c>StoreCategoryEntity</c>. /// </exception> /// <exception cref="UtnEmallDataAccessException"> /// If an DbException occurs in the try block while accessing the database. /// </exception> public void Delete(StoreCategoryEntity storeCategory) { Delete(storeCategory, null); }
/// <summary> /// Function to Save a StoreCategoryEntity in the database. /// </summary> /// <param name="storeCategory">StoreCategoryEntity 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="storeCategory"/> is not a <c>StoreCategoryEntity</c>. /// </exception> /// <exception cref="UtnEmallDataAccessException"> /// If an DbException occurs in the try block while accessing the database. /// </exception> public void Save(StoreCategoryEntity storeCategory, Dictionary <string, IEntity> scope) { if (storeCategory == null) { throw new ArgumentException("The argument can't be null"); } // Create a unique key to identify the object in the internal scope string scopeKey = storeCategory.Id.ToString(NumberFormatInfo.InvariantInfo) + "StoreCategory"; 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 (storeCategory.IsNew || !DataAccessConnection.ExistsEntity(storeCategory.Id, "StoreCategory", "idStoreCategory", dbConnection, dbTransaction)) { commandName = "SaveStoreCategory"; } else { isUpdate = true; commandName = "UpdateStoreCategory"; } // 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("@idStoreCategory", DbType.Int32); parameter.Value = storeCategory.Id; sqlCommand.Parameters.Add(parameter); } FillSaveParameters(storeCategory, sqlCommand); // Execute the command if (isUpdate) { sqlCommand.ExecuteNonQuery(); } else { IDbDataParameter parameterIdOutput = dataAccess.GetNewDataParameter("@idStoreCategory", DbType.Int32); parameterIdOutput.Direction = ParameterDirection.ReturnValue; sqlCommand.Parameters.Add(parameterIdOutput); sqlCommand.ExecuteNonQuery(); storeCategory.Id = Convert.ToInt32(parameterIdOutput.Value, NumberFormatInfo.InvariantInfo); } scopeKey = storeCategory.Id.ToString(NumberFormatInfo.InvariantInfo) + "StoreCategory"; // Add entity to current internal scope scope.Add(scopeKey, storeCategory); // 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 storeCategory.IsNew = false; storeCategory.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 StoreCategoryEntity in the database. /// </summary> /// <param name="storeCategory">StoreCategoryEntity to save</param> /// <exception cref="ArgumentNullException"> /// if <paramref name="storeCategory"/> is not a <c>StoreCategoryEntity</c>. /// </exception> /// <exception cref="UtnEmallDataAccessException"> /// If an DbException occurs in the try block while accessing the database. /// </exception> public void Save(StoreCategoryEntity storeCategory) { Save(storeCategory, null); }
/// <summary> /// Función para cargar un StoreCategoryEntity 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 StoreCategoryEntity Load(int id, bool loadRelation, Dictionary <string, IEntity> scope) { // Crea una clave para el objeto de scope interno string scopeKey = id.ToString(NumberFormatInfo.InvariantInfo) + "StoreCategory"; 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((StoreCategoryEntity)scope[scopeKey]); } } else { // Si no existe un scope, crear uno scope = new Dictionary <string, IEntity>(); } StoreCategoryEntity storeCategory = null; // Chequear si la entidad fue ya cargada por el data access actual // y retornar si fue ya cargada if (inMemoryEntities.ContainsKey(id)) { storeCategory = inMemoryEntities[id]; // Agregar el objeto actual al scope scope.Add(scopeKey, storeCategory); } 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 idStoreCategory, idCategory, idStore, timestamp FROM [StoreCategory] WHERE idStoreCategory = @idStoreCategory"; // Crea el command SqlCeCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction); // Crear el parametro id para la consulta SqlCeParameter parameter = dataAccess.GetNewDataParameter("@idStoreCategory", DbType.Int32); parameter.Value = id; sqlCommand.Parameters.Add(parameter); // Usar el datareader para cargar desde la base de datos IDataReader reader = sqlCommand.ExecuteReader(); storeCategory = new StoreCategoryEntity(); if (reader.Read()) { // Cargar las filas de la entidad storeCategory.Id = reader.GetInt32(0); storeCategory.IdCategory = reader.GetInt32(1); storeCategory.IdStore = reader.GetInt32(2); // Agregar el objeto actual al scope scope.Add(scopeKey, storeCategory); // Agregar el objeto a la cahce de entidades cargadas inMemoryEntities.Add(storeCategory.Id, storeCategory); // Lee el timestamp y establece las propiedades nuevo y cambiado storeCategory.Timestamp = reader.GetDateTime(3); storeCategory.IsNew = false; storeCategory.Changed = false; // Cerrar el Reader reader.Close(); // Carga los objetos relacionadoss if required if (loadRelation) { LoadRelationCategory(storeCategory, 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(storeCategory); }
/// <summary> /// Función que elimina un StoreCategoryEntity de la base de datos. /// </summary> /// <param name="storeCategory">StoreCategoryEntity a eliminar</param> /// <param name="scope">Estructura interna para evitar problemas de referencia circular.</param> /// <exception cref="ArgumentNullException"> /// Si <paramref name="storeCategory"/> no es un <c>StoreCategoryEntity</c>. /// </exception> /// <exception cref="UtnEmallDataAccessException"> /// Si una DbException ocurre cuando se accede a la base de datos /// </exception> public void Delete(StoreCategoryEntity storeCategory, Dictionary <string, IEntity> scope) { if (storeCategory == 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. storeCategory = this.Load(storeCategory.Id, true); if (storeCategory == null) { throw new UtnEmallDataAccessException("Error al recuperar datos al intentar eliminar."); } // Crea un nuevo command para eliminar string cmdText = "DELETE FROM [StoreCategory] WHERE idStoreCategory = @idStoreCategory"; SqlCeCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction); // Agrega los valores de los parametros SqlCeParameter parameterID = dataAccess.GetNewDataParameter("@idStoreCategory", DbType.Int32); parameterID.Value = storeCategory.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(storeCategory.Id); // Eliminamos la entidad del scope if (scope != null) { string scopeKey = storeCategory.Id.ToString(NumberFormatInfo.InvariantInfo) + "StoreCategory"; 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 StoreCategoryEntity en la base de datos. /// </summary> /// <param name="storeCategory">StoreCategoryEntity a guardar</param> /// <param name="scope">Estructura interna para evitar problemas con referencias circulares</param> /// <exception cref="ArgumentNullException"> /// Si <paramref name="storeCategory"/> no es un <c>StoreCategoryEntity</c>. /// </exception> /// <exception cref="UtnEmallDataAccessException"> /// Si una DbException ocurre cuando se accede a la base de datos /// </exception> public void Save(StoreCategoryEntity storeCategory, Dictionary <string, IEntity> scope) { if (storeCategory == null) { throw new ArgumentException("The argument can't be null"); } // Crear una clave unica para identificar el objeto dentro del scope interno string scopeKey = storeCategory.Id.ToString(NumberFormatInfo.InvariantInfo) + "StoreCategory"; 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 (storeCategory.IsNew || !DataAccessConnection.ExistsEntity(storeCategory.Id, "StoreCategory", "idStoreCategory", dbConnection, dbTransaction)) { commandName = "INSERT INTO [StoreCategory] (idStoreCategory, IDCATEGORY, IDSTORE, [TIMESTAMP] ) VALUES( @idStoreCategory, @idCategory,@idStore, GETDATE()); "; } else { isUpdate = true; commandName = "UPDATE [StoreCategory] SET idCategory = @idCategory, idStore = @idStore , timestamp=GETDATE() WHERE idStoreCategory = @idStoreCategory"; } // Se crea un command SqlCeCommand sqlCommand = dataAccess.GetNewCommand(commandName, dbConnection, dbTransaction); // Agregar los parametros del command . SqlCeParameter parameter; if (!isUpdate && storeCategory.Id == 0) { storeCategory.Id = DataAccessConnection.GetNextId("idStoreCategory", "StoreCategory", dbConnection, dbTransaction); } parameter = dataAccess.GetNewDataParameter("@idStoreCategory", DbType.Int32); parameter.Value = storeCategory.Id; sqlCommand.Parameters.Add(parameter); FillSaveParameters(storeCategory, sqlCommand); // Ejecutar el command sqlCommand.ExecuteNonQuery(); scopeKey = storeCategory.Id.ToString(NumberFormatInfo.InvariantInfo) + "StoreCategory"; // Agregar la entidad al scope actual scope.Add(scopeKey, storeCategory); // 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 storeCategory.IsNew = false; storeCategory.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; } } }
/// <summary> /// Updates the database to reflect the current state of the list. /// </summary> /// <param name="collectionDataAccess">the IDataAccess of the relation</param> /// <param name="parent">the parent of the object</param> /// <param name="collection">a collection of items</param> /// <param name="isNewParent">if the parent is a new object</param> /// <param name="scope">internal data structure to aviod problems with circular referencies on entities</param> /// <exception cref="UtnEmallDataAccessException"> /// If an DbException occurs in the try block while accessing the database. /// </exception> private void SaveStoreCategoryCollection(StoreCategoryDataAccess collectionDataAccess, StoreEntity parent, Collection <StoreCategoryEntity> collection, bool isNewParent, Dictionary <string, IEntity> scope) { if (collection == null) { return; } // Set connection objects on collection data access collectionDataAccess.SetConnectionObjects(dbConnection, dbTransaction); // Set the child/parent relation for (int i = 0; i < collection.Count; i++) { bool changed = collection[i].Changed; collection[i].Store = parent; collection[i].Changed = changed; } // If the parent is new save all childs, else check diferencies with db if (isNewParent) { for (int i = 0; i < collection.Count; i++) { collectionDataAccess.Save(collection[i], scope); } } else { // Check the childs that are not part of the parent any more string idList = "0"; if (collection.Count > 0) { idList = "" + collection[0].Id; } for (int i = 1; i < collection.Count; i++) { idList += ", " + collection[i].Id; } // Returns the ids that doesn't exists in the current collection string command = "SELECT idStoreCategory FROM [StoreCategory] WHERE idStore = @idStore AND idStoreCategory NOT IN (" + idList + ")"; IDbCommand sqlCommand = dataAccess.GetNewCommand(command, dbConnection, dbTransaction); IDbDataParameter sqlParameterId = dataAccess.GetNewDataParameter("@idStore", DbType.Int32); sqlParameterId.Value = parent.Id; sqlCommand.Parameters.Add(sqlParameterId); IDataReader reader = sqlCommand.ExecuteReader(); Collection <StoreCategoryEntity> objectsToDelete = new Collection <StoreCategoryEntity>(); // Insert Ids on a list List <int> listId = new List <int>(); while (reader.Read()) { listId.Add(reader.GetInt32(0)); } reader.Close(); // Load items to be removed foreach (int id in listId) { StoreCategoryEntity entityToDelete = collectionDataAccess.Load(id, scope); objectsToDelete.Add(entityToDelete); } // Have to do this because the reader must be closed before // deletion of entities for (int i = 0; i < objectsToDelete.Count; i++) { collectionDataAccess.Delete(objectsToDelete[i], scope); } System.DateTime timestamp; // Check all the properties of the collection items // to see if they have changed (timestamp) for (int i = 0; i < collection.Count; i++) { StoreCategoryEntity item = collection[i]; if (!item.Changed && !item.IsNew) { // Create the command string sql = "SELECT timestamp FROM [StoreCategory] WHERE idStoreCategory = @idStoreCategory"; IDbCommand sqlCommandTimestamp = dataAccess.GetNewCommand(sql, dbConnection, dbTransaction); // Set the command's parameters values IDbDataParameter sqlParameterIdPreference = dataAccess.GetNewDataParameter("@idStoreCategory", DbType.Int32); sqlParameterIdPreference.Value = item.Id; sqlCommandTimestamp.Parameters.Add(sqlParameterIdPreference); timestamp = ((System.DateTime)sqlCommandTimestamp.ExecuteScalar()); if (item.Timestamp != timestamp) { item.Changed = true; } } // Save the item if it changed or is new if (item.Changed || item.IsNew) { collectionDataAccess.Save(item); } } } }
/// <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 SaveStoreCategoryCollection(StoreCategoryDataAccess collectionDataAccess, StoreEntity parent, Collection <StoreCategoryEntity> 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].Store = 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 idStoreCategory FROM [StoreCategory] WHERE idStore = @idStore AND idStoreCategory NOT IN (" + idList + ")"; SqlCeCommand sqlCommand = dataAccess.GetNewCommand(command, dbConnection, dbTransaction); SqlCeParameter sqlParameterId = dataAccess.GetNewDataParameter("@idStore", DbType.Int32); sqlParameterId.Value = parent.Id; sqlCommand.Parameters.Add(sqlParameterId); IDataReader reader = sqlCommand.ExecuteReader(); Collection <StoreCategoryEntity> objectsToDelete = new Collection <StoreCategoryEntity>(); // 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) { StoreCategoryEntity 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++) { StoreCategoryEntity item = collection[i]; if (!item.Changed && !item.IsNew) { // Crea el command string sql = "SELECT timestamp FROM [StoreCategory] WHERE idStoreCategory = @idStoreCategory"; SqlCeCommand sqlCommandTimestamp = dataAccess.GetNewCommand(sql, dbConnection, dbTransaction); // Establece los datos a los parametros del command SqlCeParameter sqlParameterIdPreference = dataAccess.GetNewDataParameter("@idStoreCategory", 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) { store = new StoreEntity(); } store.Name = TxtName.Text.Trim(); store.TelephoneNumber = TxtPhone.Text.Trim(); store.ContactName = TxtContact.Text.Trim(); store.WebAddress = TxtWebsite.Text.Trim(); store.Email = TxtEmail.Text.Trim(); store.LocalNumber = TxtNumber.Text.Trim(); store.InternalPhoneNumber = TxtInternalPhone.Text.Trim(); store.OwnerName = TxtOwner.Text.Trim(); System.Collections.Generic.List <StoreCategoryEntity> toRemove = new System.Collections.Generic.List <StoreCategoryEntity>(); // si las categorías fueron modificadas if (this.categoriesLoaded) { // recorremos todas las categorías de la tienda foreach (StoreCategoryEntity storeCategory in store.StoreCategory) { bool exists = false; foreach (CategoryEntity category in categoryWindow.Selected) { // no se puede eliminar una categoría que ya está seleccionada if (storeCategory.Category.Name == category.Name) { exists = true; break; } } if (!exists) { toRemove.Add(storeCategory); } } foreach (StoreCategoryEntity storeCategory in toRemove) { store.StoreCategory.Remove(storeCategory); } // recorremos todas las categorías seleccionadas foreach (CategoryEntity category in categoryWindow.Selected) { bool exists = false; foreach (StoreCategoryEntity storeCategory in store.StoreCategory) { if (storeCategory.Category.Name == category.Name) { exists = true; break; } } if (!exists) { StoreCategoryEntity newStoreCategory = new StoreCategoryEntity(); newStoreCategory.Category = category; store.StoreCategory.Add(newStoreCategory); } } } }