public IActionResult AddAccount(AccountCreatorModel account) { int userId = HttpContext.Session.Get <int>(Session_Key); int accountId = accountDAL.CreateAccount(account); accountDAL.AddAccountToUser(accountId, userId); return(RedirectToAction("index")); }
/// <summary> /// Adds a new account to the Database /// </summary> /// <param name="account">The account to be added</param> /// <returns>The ID number of the new account</returns> public int CreateAccount(AccountCreatorModel account) { int accountId = 0; try { using (SqlConnection conn = new SqlConnection(ConnectionString)) { conn.Open(); string sql = "INSERT INTO accounts (account_name, account_type, account_number) VALUES (@name, @type, @number);"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("@name", account.Name); cmd.Parameters.AddWithValue("@type", account.Type); // Generate a random Account Number Random random = new Random(); int newNumber = random.Next(1000000000); while (!IsAvailableNumber(newNumber)) { newNumber = random.Next(1000000000); } string newAccountNumber = newNumber.ToString("000000000"); cmd.Parameters.AddWithValue("@number", newAccountNumber); cmd.ExecuteNonQuery(); sql = $"SELECT account_id FROM accounts WHERE account_number = {newNumber};"; cmd = new SqlCommand(sql, conn); SqlDataReader reader = cmd.ExecuteReader(); reader.Read(); accountId = Convert.ToInt32(reader["account_id"]); } } catch (SqlException ex) { Console.WriteLine(ex.Message); } return(accountId); }