public static void CarregarBase() { var Alface = new Ingrediente { Id = 1, Nome = "Alface", Preco = 0.40m }; var Bacon = new Ingrediente { Id = 2, Nome = "Bacon", Preco = 2.00m }; var Hamburguer = new Ingrediente { Id = 3, Nome = "Hambúrguer de carne", Preco = 3.00m }; var Ovo = new Ingrediente { Id = 4, Nome = "Ovo", Preco = 0.80m }; var Queijo = new Ingrediente { Id = 5, Nome = "Queijo", Preco = 1.50m }; Ingredientes.AddRange(new List <Ingrediente> { Alface, Bacon, Hamburguer, Ovo, Queijo }); }
public IActionResult Post([FromBody] Ingrediente ingrediente) { Response oResponse = new Response(); try { var flag = _ingredienteService.ValIngrediente(ingrediente); if (flag == true) { _ingredienteService.Add(ingrediente); oResponse.Code = 1; oResponse.Data = ingrediente; oResponse.Message = "ingrediente registrado con exito"; } else { oResponse.Code = 0; oResponse.Message = "ingrediente ya existente"; } } catch (Exception e) { oResponse.Message = "error al registrar " + e.Message; } return(Ok(oResponse)); }
protected void GridExtrasAgregados_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { GridViewRow row = e.Row; LinkButton btnAdd = (LinkButton)row.FindControl("btnPlus"); LinkButton btnSubstract = (LinkButton)row.FindControl("btnMinus"); int idIngrediente = Convert.ToInt32((row.FindControl("lblCodigo") as Label).Text); Label lblElementoPedido = e.Row.Parent.Parent.Parent.FindControl("lblCodigoElementoPedido") as Label; Label lblIdAlimento = e.Row.Parent.Parent.Parent.FindControl("lblCodigo") as Label; Ingrediente ingrediente = iDAL.Find(idIngrediente); ExtraPedido extraPedido = carrito.GetListExtra().FirstOrDefault(x => x.IdIngrediente == idIngrediente && x.IdAlimentoPedido == int.Parse(lblElementoPedido.Text)); ExtraDisponible extraDisponible = eDDAL.FindByAlimentoAndIngrediente(int.Parse(lblIdAlimento.Text), idIngrediente); Label lblIngrediente = row.FindControl("lblIngrediente") as Label; Label lblCantidad = row.FindControl("lblCantidad") as Label; Label lblValor = row.FindControl("lblValor") as Label; lblIngrediente.Text = ingrediente.Nombre; lblCantidad.Text = $"{ingrediente.Porción * extraPedido.CantidadExtra} {tMDAL.Find(ingrediente.IdTipoMedicionPorcion.Value).Descripcion}"; int valor = extraDisponible.Valor.HasValue ? extraPedido.CantidadExtra.Value * extraDisponible.Valor.Value : 0; lblValor.Text = $"{ valor }"; btnAdd.Enabled = extraPedido == null || extraPedido.CantidadExtra != extraDisponible.CantidadMaxima; btnSubstract.Enabled = extraPedido != null; } }
public async Task <IActionResult> PutIngrediente(Guid id, Ingrediente ingrediente) { if (id != ingrediente.Id) { return(BadRequest()); } _context.Entry(ingrediente).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!IngredienteExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> Edit(int id, [Bind("Id,Nombre,Foto")] Ingrediente ingrediente) { if (id != ingrediente.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(ingrediente); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!IngredienteExists(ingrediente.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(ingrediente)); }
public void crearIngrediente(Ingrediente ingrediente) { using (var conn = new SqlConnection(this.CONECCION_STRING)) { conn.Open(); // 1. create a command object identifying the stored procedure SqlCommand cmd = new SqlCommand("crearIngrediente", conn); // 2. set the command object so it knows to execute a stored procedure cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@nombreIngrediente", ingrediente.obtenerNombreIngrediente())); cmd.Parameters.Add(new SqlParameter("@precioIngrediente", ingrediente.obtenerValorIngrediente())); cmd.Parameters.Add(new SqlParameter("@cantidadDisponible", ingrediente.obtnerCantidaddisponible())); // execute the command using (SqlDataReader rdr = cmd.ExecuteReader()) { // iterate through results, printing each to console while (rdr.Read()) { Console.WriteLine("Product: {0,-35} Total: {1,2}", rdr["nombreIngrediente"], rdr["precioIngrediente"]); } } conn.Close(); } }
private void ListIngredientes_SelectedIndexChanged(object sender, EventArgs e) { _ingrediente = new Ingrediente(); _ingrediente = (Ingrediente)listIngredientes.SelectedItem; btnLimpiarIngredientes.Enabled = true; }
public async Task <int> modificarIngrediente(Ingrediente i) { int modificado = 0; try { limpiarListas(); listaParam.Add("id_product"); listaParam.Add("name"); listaParam.Add("price"); listaParam.Add("image"); listaValues.Add(i.getIdProducto().ToString()); listaValues.Add(i.getNombre()); listaValues.Add(i.getPrecio().ToString()); listaValues.Add(i.getImagen()); String json = await hreq.sendRequestPOST("/ServicioMyPizza/servicios/WSProducto/modificarproducto", listaParam, listaValues); modificado = JsonConvert.DeserializeObject <int>(json); } catch (System.Net.WebException swe) { modificado = 0; } return(modificado); }
public IActionResult GetIngrediente(int receita, int id) { Ingrediente i = receitaHandling.GetIngrediente(id); ViewBag.idReceita = receita; return(View(i)); }
public ActionResult CadastrarIngrediente(Ingrediente ingrediente, int?Categorias) { ViewBag.Categorias = new SelectList(CategoriaDAO.RetornarCategorias(), "IdCategoria", "NomeCategoria"); if (ModelState.IsValid) { if (Categorias != null) { ingrediente.CategoriaIngrediente = CategoriaDAO.BuscarCategoriaPorId(Categorias); if (IngredienteDAO.CadastrarIngrediente(ingrediente)) { return(RedirectToAction("Home", "Ingrediente")); } else { ModelState.AddModelError("", "Não é possível adicionar um ingrediente com o mesmo nome!"); return(View(ingrediente)); } } else { ModelState.AddModelError("", "Por favor, selecione uma categoria!"); return(View(ingrediente)); } } else { return(View()); } }
public async Task <IActionResult> Edit(int id, [Bind("IDIngrediente,Descripcion,IDInventarioIngre")] Ingrediente ingrediente) { if (id != ingrediente.IDIngrediente) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(ingrediente); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!IngredienteExists(ingrediente.IDIngrediente)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["IDInventarioIngre"] = new SelectList(_context.InventarioIngredientes, "IDInventarioIngre", "IDInventarioIngre", ingrediente.IDInventarioIngre); return(View(ingrediente)); }
protected void GridViewExtrasDisponibles_RowCommand(object sender, GridViewCommandEventArgs e) { try { if (!string.IsNullOrEmpty(e.CommandArgument.ToString())) { int index = Convert.ToInt32(e.CommandArgument); Label codigo = (Label)GridViewExtrasDisponibles.Rows[index].FindControl("lblIdIngrediente"); int id = Convert.ToInt32(codigo.Text); Ingrediente ingrediente = iDAL.Find(id); switch (e.CommandName) { case "Quitar": listaExtras.SubstractOne(ingrediente); break; case "Agregar": listaExtras.AddIngrediente(ingrediente); break; } LoadGridExtrasDisponibles(); } } catch (Exception ex) { UserMessage(ex.Message, "danger"); } }
public ActionResult Delete(int?ingredienteId, int?receitaId) { // Cria um par chave-valor, com "id" - ReceitaID var routeValue = new RouteValueDictionary(); routeValue.Add("id", receitaId); if (ingredienteId != null) { Ingrediente ingrediente = db.Ingrediente.Find(ingredienteId); if (ingrediente != null) { // Cria um par chave-valor, com "id" - ReceitaID var routeValue2 = new RouteValueDictionary(); routeValue2.Add("id", ingrediente.ReceitaID); // Deleto o ingrediente da receita Ingrediente.DeletarIngrediente(ingrediente.IngredienteID); return(RedirectToAction("Edit", "Receitas", routeValue2)); } } return(RedirectToAction("Edit", "Receitas", routeValue)); }
public ActionResult DeleteConfirmed(int id) { Ingrediente ingrediente = IngredienteDAO.BuscarIngredientePorId(id); IngredienteDAO.RemoverIngrediente(ingrediente); return(RedirectToAction("Index")); }
static void Main(string[] args) { int tipoIng; Console.WriteLine("Digite o nome do ingrediente: "); string nomeIng = Console.ReadLine(); do { Console.WriteLine("Digite o tipo de ingrediente:\nSendo:\n-1- para Pão\n-2- para Carne\n-3- para Extra"); tipoIng = int.Parse(Console.ReadLine()); if (tipoIng < 1 || tipoIng > 3) { Console.WriteLine("Tipo inválido, tente novamente."); } ; } while (tipoIng < 1 || tipoIng > 3); using (var db = new hamburgueriaContext()) { var novoIng = new Ingrediente { Id = Guid.NewGuid().ToString(), Nome = nomeIng, TipoIngredienteId = tipoIng, }; db.Ingrediente.Add(novoIng); db.SaveChanges(); } }
public bool Update(Ingrediente t) { TipoIngrediente tpingrediente = tpingredienteRepository.FindById(t.CTipoIngrediente.CTipoIngrediente); t.CTipoIngrediente = tpingrediente; return(ingredienteRepository.Update(t)); }
public DataTable GetDataTable(int idAlimentoPedido) { DataTable dt = new DataTable(); dt.Columns.Add("IdExtraPedido"); dt.Columns.Add("CantidadExtra"); dt.Columns.Add("IdIngrediente"); dt.Columns.Add("IdTipoMedicion"); dt.Columns.Add("ValorExtra"); string[] reg = new string[dt.Columns.Count]; foreach (ExtraPedido item in GetListByAlimentoPedido(idAlimentoPedido)) { Ingrediente obj = iDAL.Find((int)item.IdIngrediente); reg[0] = item.IdExtraPedido.ToString(); reg[1] = item.CantidadExtra.ToString(); reg[2] = item.IdIngrediente.ToString(); reg[3] = obj.IdTipoMedicion.ToString(); reg[4] = item.ValorExtra.HasValue? $"${item.ValorExtra.ToString()}": "Sin costo"; dt.Rows.Add(reg); } return(dt); }
public bool Insert(Ingrediente t) { TipoIngrediente tpingrediente = tpingredienteRepository.FindById(t.CTipoIngrediente.CTipoIngrediente); t.CTipoIngrediente = tpingrediente; return(ingredienteRepository.Insert(t)); }
public void CarregarCampos(Ingrediente ingr) { txtDescricao.Text = ingr.Descricao; txtPreco.Text = ingr.Preco.ToString(); cbxUnidade.Text = ingr.Unidade.ToString(); dtpDataCadastro.Value = ingr.DataCadastro; }
public FormCadIngrediente(IngredienteController controller, Ingrediente ingredienteEdicao) { InitializeComponent(); this.controller = controller; this.ingrediente = ingredienteEdicao; CarregarCampos(ingredienteEdicao); }
protected void gridViewIngredientesAlimento_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { GridViewRow row = e.Row; Label lblCodigo = row.FindControl("lblCodigo") as Label; Ingrediente ingrediente = iDAL.Find(Convert.ToInt32(lblCodigo.Text)); Label label = (Label)row.FindControl("lblNombre"); label.Text = ingrediente.Nombre; label = (Label)row.FindControl("lblDescripcion"); label.Text = ingrediente.Descripcion; label = (Label)row.FindControl("lblMarca"); DetalleIngrediente detalle = iDAL.GetDetalleByDefault(ingrediente.IdIngrediente); label.Text = detalle.IdMarca.HasValue ? mDAL.Find(Convert.ToInt32(detalle.IdMarca.Value)).Nombre : "Sin Marca"; label = (Label)row.FindControl("lblCantidad"); int cantidad = int.Parse(label.Text); label = (Label)row.FindControl("lblCantidadTotal"); label.Text = $"{ingrediente.Porción * cantidad} {tMDAL.Find(ingrediente.IdTipoMedicionPorcion.Value).Descripcion}"; } }
private bool verificarStock(Alimento ali) { bool existeStock = true; int idAlimento = ali.IdAlimento; List <Ingrediente> ingredientes = iDAL.GetAll(); /* * var ingredientes corresponde a todos los ingredientes de la base de datos * Se le deben restar todas las cantidades por cada preparación en el carrito * */ foreach (AlimentoPedido item in alimentos) { //Se hace una nueva lista de ingredientes por cada preparación en el carrito List <IngredientesAlimento> lista = iADAL.GetIngredientesByAlimento((int)item.IdAlimento); // A cada ingrediente se le resta el stock correcpondiente a cada preparación // de esta forma se hace una simulación de datos de la BDD foreach (IngredientesAlimento xx in lista) { Ingrediente ingrediente = ingredientes.FirstOrDefault(x => x.IdIngrediente == xx.Ingrediente); if (ingrediente.Stock < xx.Cantidad) { existeStock = false; throw new Exception("No hay suficiente " + ingrediente.Nombre + " para preparar " + ali.Nombre); } else { ingrediente.Stock -= xx.Cantidad; } } } return(existeStock); }
protected void gridViewIngredientesAlimento_RowCommand(object sender, GridViewCommandEventArgs e) { try { int index = Convert.ToInt32(e.CommandArgument); Label codigo = (Label)gridViewIngredientesAlimento.Rows[index].FindControl("lblCodigo"); int id = Convert.ToInt32(codigo.Text); Ingrediente ingrediente = iDAL.Find(id); switch (e.CommandName) { case "Quitar": listaIngrediente.SubstractOne(ingrediente); break; case "Agregar": listaIngrediente.AddIngrediente(ingrediente); break; } LoadGridIngredienteAlimento(); } catch (Exception ex) { UserMessage(ex.Message, "danger"); } }
static void Main(string[] args) { string ingrediente; int tipo; Console.WriteLine("Olá usuário, digite o nome do novo ingrediente:"); ingrediente = Console.ReadLine(); Console.WriteLine("Qual o tipo (1, 2 ou 3)?"); tipo = Convert.ToInt32(Console.ReadLine()); using (var db = new hamburgueriaContext()) { var novoIngrediente = new Ingrediente { Id = Guid.NewGuid().ToString(), Nome = ingrediente, TipoIngredienteId = tipo, }; db.Ingrediente.Add(novoIngrediente); db.SaveChanges(); } Console.WriteLine("Ingrediente incluso. Pressione qualquer tecla para finalizar:"); Console.ReadKey(); }
protected void GridViewExtrasDisponibles_RowDataBound(object sender, GridViewRowEventArgs e) { try { if (e.Row.RowType == DataControlRowType.DataRow) { GridViewRow row = e.Row; int idIngrediente = 0; Label lbl = row.FindControl("lblIngrediente") as Label; idIngrediente = string.IsNullOrEmpty(lbl.Text) ? 0 : Convert.ToInt32(lbl.Text); lbl.Text = string.IsNullOrEmpty(lbl.Text) ? "Sin Ingrediente" : iDAL.Find(Convert.ToInt32(lbl.Text)).Nombre; lbl = (Label)row.FindControl("lblValor"); if (lbl != null) { lbl.Text = string.IsNullOrEmpty(lbl.Text) ? "0" : lbl.Text; } lbl = (Label)row.FindControl("lblCantidad"); int cantidad = string.IsNullOrEmpty(lbl.Text) ? 0 : Convert.ToInt32(lbl.Text); lbl = (Label)row.FindControl("lblPorcion"); Ingrediente i = iDAL.Find(idIngrediente); int cantidadPorcion = i.Porción.HasValue ? i.Porción.Value * cantidad : 0; string nombrePorcion = i.IdTipoMedicionPorcion.HasValue ? tMDAL.Find(i.IdTipoMedicionPorcion.Value).Descripcion : ""; lbl.Text = cantidadPorcion == 0 ? "Porción no Ingresada" : $"{cantidadPorcion} {nombrePorcion}"; } } catch (Exception ex) { UserMessage(ex.Message, "danger"); } }
public async Task <IActionResult> Edit(int id, [Bind("IngredienteId,NomeIngrediente,ValorIngrediente,NomeMontado,IngrdientesUsados,ValorMontado")] Ingrediente ingrediente) { if (id != ingrediente.IngredienteId) { return(NotFound()); } if (ModelState.IsValid) { if (ingrediente.NomeIngrediente != null) { await _ingredienteRepositorio.Atualizar(ingrediente); TempData["Atualizacao"] = $"Ingrediente {ingrediente.NomeIngrediente} inserido com sucesso"; return(RedirectToAction(nameof(Index))); } else if (ingrediente.NomeMontado != null) { await _ingredienteRepositorio.Atualizar(ingrediente); TempData["Atualizacao"] = $"Lanche montado {ingrediente.NomeIngrediente} inserido com sucesso"; return(RedirectToAction(nameof(Index))); } } return(View(ingrediente)); }
private void EliminarRegistro() { if (this.gridView1.IsFocusedView) { Ingrediente Registro = (Ingrediente)this.bs.Current; if (Registro == null) { return; } if (MessageBox.Show("Esta seguro de eliminar este registro", "Atencion", MessageBoxButtons.YesNo) != DialogResult.Yes) { return; } try { db.DeleteObject(Registro); db.SaveChanges(); Busqueda(); } catch (Exception x) { MessageBox.Show(x.Message); } } }
public async Task <ActionResult <Ingrediente> > PostIngrediente(Ingrediente ingrediente) { _context.Ingrediente.Add(ingrediente); await _context.SaveChangesAsync(); return(CreatedAtAction("GetIngrediente", new { id = ingrediente.Id }, ingrediente)); }
public ActionResult AlterarIngrediente(Ingrediente ingredienteAlterado, int?Categorias) { ViewBag.Categorias = CategoriaDAO.RetornarCategorias(); ingredienteAlterado.CategoriaIngrediente = CategoriaDAO.BuscarCategoriaPorId(Categorias); Ingrediente ingredienteOriginal = IngredienteDAO.BuscarIngredientePorId(ingredienteAlterado.IdIngrediente); if (ModelState.IsValid && Categorias != null) { ingredienteOriginal.NomeIngrediente = ingredienteAlterado.NomeIngrediente; ingredienteOriginal.PrecoIngrediente = ingredienteAlterado.PrecoIngrediente; ingredienteOriginal.PesoIngrediente = ingredienteAlterado.PesoIngrediente; ingredienteOriginal.CategoriaIngrediente = ingredienteAlterado.CategoriaIngrediente; ingredienteOriginal.StatusIngrediente = ingredienteAlterado.StatusIngrediente; if (IngredienteDAO.AlterarIngrediente(ingredienteOriginal)) { return(RedirectToAction("Home", "Ingrediente")); } else { ModelState.AddModelError("", "Não é possível alterar um ingrediente com o mesmo nome!"); return(View(ingredienteOriginal)); } } else { ModelState.AddModelError("", "Selecione uma Categoria Válida!"); return(View(ingredienteOriginal)); } }
public FormGerente() { InitializeComponent(); FormBorderStyle = FormBorderStyle.None; WindowState = FormWindowState.Maximized; //Tamaño.CargarTamaños(); Hamburguesa.CargarHamburguesas(); Bebida.CargarBebidas(); Carne.CargarCarnes(); Ingrediente.CargarIngredientes(); Postre.CargarPostres(); Nuggets.CargarNuggets(); MostrarB(); MostrarC(); MostrarH(); MostrarSH(); ActualizarCmb(); OcultarBtnBebidas(); OcultarBtnHamburguesas(); OcultarBtnCombo(); pnlNugget.Enabled = false; cmbHamburguesa.Enabled = false; CargarPie1(); CargarPie2(); PBModificarC.Hide(); }
public bool CreateIngrediente(string nombre, short tipo, decimal cantidad) { Ingrediente newIngrediente = new Ingrediente { Nombre = nombre, Tipo = tipo, Cantidad = cantidad }; return ingrediente_persistence.Create(newIngrediente); }
public bool ValidateNewIngrediente(string nombre,short tipo,decimal cantidad) { Ingrediente i=new Ingrediente { Nombre = nombre, Tipo = tipo, Cantidad = cantidad }; bool valid = !string.IsNullOrEmpty(i.Nombre) ? true : false; bool tmp = i.Tipo > 0 ? true : false; valid = valid && tmp; tmp = i.Cantidad > 0 ? true : false; valid = valid && tmp; return valid; }
// Operations /// <summary> /// Ingresar un nuevo ingrediente a la base de datos /// </summary> /// <param name="nuevo_ingrediente"> /// Objeto ingrediente que se desea ingresar /// </param> /// <returns> /// Retorna verdadero si se ingreso el ingrediente, falso si no se ingreso. /// </returns> public bool nuevo_Ingrediente(Ingrediente nuevo_ingrediente) { /* {author=Andrés Olmos}*/ // section -84-17-6-96-22000729:15110a8e74c:-8000:0000000000000FA9 begin // section -84-17-6-96-22000729:15110a8e74c:-8000:0000000000000FA9 end }
public void setIngredientesUsados(Ingrediente ing) { ingredientes.Add(ing); }
/// <summary> /// Modificar ingrediente de la base de datos /// </summary> /// <param name="id_ingrediente"> /// Identificador del ingrediente que se desea modificar /// </param> /// <param name="nuevos_datos_ingrediente"> /// Objeto ingrediente que reemplazara al objeto de la base de datos /// </param> /// <returns> /// Retorna verdadero si se modifico el ingrediente, false si no se logro modificar el ingrediente /// </returns> public bool modifica_Ingrediente(int id_ingrediente, Ingrediente nuevos_datos_ingrediente) { /* {author=Andrés Olmos, version=1.1.0, deprecated=true}*/ // section -84-17-6-96-22000729:15110a8e74c:-8000:0000000000000FB4 begin // section -84-17-6-96-22000729:15110a8e74c:-8000:0000000000000FB4 end }
public static List<Plato> datosPlatosProd(int id) { List<Plato> platos = new List<Plato>(); string connectionString = ConfigurationManager.ConnectionStrings["TiendaConString"].ConnectionString; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand("platosProduccion", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("dProduccion", id); try { connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { Plato plato = new Plato(); plato.Id = reader.GetInt32(0); plato.Costo = reader.GetDecimal(2); //recuperar los ingredientes de los platos en una lista de lista SqlCommand commandI = new SqlCommand("ingredienteDetalle", connection); commandI.CommandType = CommandType.StoredProcedure; commandI.Parameters.AddWithValue("idPlato", plato.Id); commandI.Parameters.AddWithValue("cantidad", plato.Costo); SqlDataReader readerI = commandI.ExecuteReader(); while (readerI.Read()) { Ingrediente ing = new Ingrediente(); ing.Unidad.Nombre = readerI[3].ToString(); ing.Cantidad = Validar.ConvertirAKilo(ing.Unidad.Nombre, (float)readerI.GetDouble(2)); plato.setIngredientes(ing); } platos.Add(plato); } } catch (SqlException ex) { throw ex; } catch (Exception ex) { throw ex; } } return platos; }
/// <summary> /// Cogemos la lista de ingredientes y detectamos cuales existen en BBDD y cuales no para añadir los que no existen. /// </summary> /// <param name="ingredientes">La lista de ingredientes.</param> private void DetectNewIngredients(List<String> ingredientes) { List<Ingrediente> ingreDB = db.Ingredientes.ToList(); List<Ingrediente> newIngredientes = new List<Ingrediente>(); foreach (String ingre in ingredientes) { bool existeIngrediente = false; //Recorremos los ingredientes de BBDD. foreach (Ingrediente item in ingreDB) { //Comprobamos si el ingrediente de la lista del bocadillo existe ya en BBDD o no. if (ingre.ToLower().Equals(item.Nombre.ToLower())) { //Ya existe en la BBDD. //Saltamos de ese ingrediente. existeIngrediente = true; break; } } //Comprobamos los que existen y los que no, y los vamos añadiendo. if (!existeIngrediente) { //No existe, creamos el ingrediente. Ingrediente newIngrediente = new Ingrediente() { Nombre = ingre, Descripcion = ingre, FechaCreacion = DateTime.Now, IdUsuario = 7 }; //Lo añadimos a la lista para agregar a BBDD. newIngredientes.Add(newIngrediente); } } //Insertamos los elementos en BBDD. foreach (Ingrediente item in newIngredientes) { //Lo insertamos en BBDD. db.Ingredientes.AddObject(item); db.SaveChanges(); } }
public static List<Ingrediente> BuuscarIngrediente(int idIngrediente) { string connectionString = ConfigurationManager.ConnectionStrings["TiendaConString"].ConnectionString; // Proporcionar la cadena de consulta // string queryString = "Select IdPersona, Nombre, ApPaterno from Persona where Nombre like '%{0}%' or ApPaterno like '%{1}%'"; //Lista de Clientes recuperados List<Ingrediente> listaIngrediente = new List<Ingrediente>(); // Crear y abrir la conexión en un bloque using. // Esto asegura que todos los recursos serán cerrados // y dispuestos cuando el código sale using (SqlConnection connection = new SqlConnection(connectionString)) { // Crear el objeto Command. SqlCommand command = new SqlCommand("infoIngrediente", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("idIngrediente", idIngrediente); // Abre la conexión en un bloque try / catch // Crear y ejecutar el DataReader, escribiendo // el conjunto de resultados a la ventana de la consola. try { connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.HasRows) { while (reader.Read()) { Ingrediente ing = new Ingrediente(); ing.Id = reader.GetInt32(0); ing.IdPlato = reader.GetInt32(1); ing.Cantidad = (float)reader.GetDouble(2); ing.IdUnidad = reader.GetInt32(3); ing.IdProducto = reader.GetInt32(4); listaIngrediente.Add(ing); } reader.NextResult(); } reader.Close(); } catch (SqlException ex) { throw ex; } catch (Exception ex) { throw ex; } } return listaIngrediente; }
public static Plato infPalto(int idPlato, float cantPlatos) { Plato plato = new Plato(); string connectionString = ConfigurationManager.ConnectionStrings["TiendaConString"].ConnectionString; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand("INF_PLATO", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("cantPlato", cantPlatos); command.Parameters.AddWithValue("idplato", idPlato); try { connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { plato.Id = reader.GetInt32(0); plato.Nombre = reader[1].ToString(); plato.Costo = reader.GetDecimal(2); reader.NextResult(); while (reader.Read()) { Ingrediente ingrediente = new Ingrediente(); ingrediente.IdProducto = reader.GetInt32(0); ingrediente.Cantidad = (float)reader.GetDouble(1); ingrediente.Unidad.Nombre = reader[2].ToString(); plato.setIngredientes(ingrediente); } } } catch (SqlException ex) { throw ex; } catch (Exception ex) { throw ex; } } return plato; }