public static Ingredient GetIngredientByID(int id) { Ingredient ingredient = null; // Select ingredient using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlServer"].ConnectionString)) { using (SqlCommand command = new SqlCommand("db_datareader.Ingredient_Select", connection)) { command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@IngredientID", id); connection.Open(); using (SqlDataReader dataReader = command.ExecuteReader()) { if (dataReader.HasRows && dataReader.Read()) { ingredient = new Ingredient(id, (string)dataReader["IngredientName"], Convert.ToInt32(dataReader["IngredientQuantity"]), new Unit(Convert.ToInt32(dataReader["UnitID"]), (string)dataReader["UnitName"], (string)dataReader["UnitAbbreviation"]) ); } } // SqlDataReader } // SqlCommand } // SqlConnection return ingredient; }
public static Ingredient Create(string name, int quantity, Unit unit) { Ingredient ingredient; // Insert new ingredient using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlServer"].ConnectionString)) { using (SqlCommand command = new SqlCommand("dbo.Ingredient_Insert", connection)) { command.CommandType = CommandType.StoredProcedure; //command.Parameters.AddWithValue("@IngredientID", 0).Direction = ParameterDirection.Output; command.Parameters.Add("@IngredientID", SqlDbType.Int); command.Parameters["@IngredientID"].Direction = ParameterDirection.Output; command.Parameters.AddWithValue("@IngredientName", name); command.Parameters.AddWithValue("@IngredientQuantity", quantity); command.Parameters.AddWithValue("@UnitID", unit.Id); connection.Open(); command.ExecuteNonQuery(); ingredient = new Ingredient((int)command.Parameters["@IngredientID"].Value, name, quantity, unit); connection.Close(); } // SqlCommand } // SqlConnection return ingredient; }