public static MenuClass saveMenu(MenuClass m) { MySqlConnection conexion = null; try { conexion = getConnection(); conexion.Open(); MySqlTransaction myTrans = conexion.BeginTransaction(); MySqlCommand comando = new MySqlCommand("SELECT id FROM Menu WHERE nombre=@nombre and fk_Perfil=@perfil", conexion); comando.Parameters.AddWithValue("@nombre", m.nombre); comando.Parameters.AddWithValue("@perfil", m.idPerfil); MySqlDataReader reader = comando.ExecuteReader(); if (!reader.HasRows) { reader.Close(); comando = new MySqlCommand("INSERT INTO Menu VALUES (null, @nombreMenu, 0, @fkPerfil)", conexion); comando.Transaction = myTrans; comando.Parameters.AddWithValue("@nombreMenu", m.nombre); comando.Parameters.AddWithValue("@fkPerfil", m.idPerfil); comando.ExecuteNonQuery(); myTrans.Commit(); comando.Parameters.Clear(); reader.Close(); comando = new MySqlCommand("SELECT id FROM Menu WHERE nombre=@nombre and fk_Perfil=@perfil", conexion); comando.Parameters.AddWithValue("@nombre", m.nombre); comando.Parameters.AddWithValue("@perfil", m.idPerfil); reader = comando.ExecuteReader(); if (reader.HasRows) { reader.Read(); Int32 id = (Int32)reader["id"]; m.id = id; return(m); } return(m); } } catch (MySqlException e) { Console.WriteLine("No se ha podido añadir el menu:\n" + e); throw e; } finally { if (conexion != null) { conexion.Close(); } } return(null); }
public static List <MenuClass> loadMenus(long id) { List <MenuClass> menus = new List <MenuClass>(); MySqlConnection conexion = null; try { conexion = getConnection(); conexion.Open(); MySqlTransaction myTrans = conexion.BeginTransaction(); MySqlCommand comando = new MySqlCommand("SELECT id,nombre,numCarps FROM Menu WHERE fk_Perfil=@fkPerfil", conexion); comando.Parameters.AddWithValue("@fkPerfil", id); MySqlDataReader reader = comando.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { Int32 idMenu = (Int32)reader["id"]; Int32 numCarp = (Int32)reader["numCarps"]; MenuClass menu = new MenuClass((long)idMenu, reader["nombre"].ToString(), (long)numCarp, id); menus.Add(menu); } reader.Close(); conexion.Close(); return(menus); } } catch (MySqlException e) { Console.WriteLine("Error al cargar los menus:+\n" + e); throw e; } finally { if (conexion != null) { conexion.Close(); } } return(null); }