BathhouseManagment/Database/DiscountRepository.cs

118 lines
3.5 KiB
C#

using System;
using System.Collections.Generic;
using BathHouseManagmet.Models;
using Microsoft.Extensions.Options;
using MySqlConnector;
namespace BathHouseManagmet.Database;
public class DiscountRepository
{
MySqlConnection connection;
public DiscountRepository(IOptions<DatabaseConnection> connect)
{
connection = new MySqlConnection(connect.Value.ConnectionString);
}
public List<Discount> GetDiscounts()
{
List<Discount> result = new();
string sql = "select * from `discount`";
try
{
connection.Open();
using (var command = new MySqlCommand(sql, connection))
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
result.Add(new Discount
{
Id = reader.GetInt32("id"),
Name = reader.GetString("name"),
Description = reader.GetString("description"),
DiscountPercent = reader.GetInt32("discount_percent")
});
}
}
connection.Close();
}
catch (Exception e)
{
Console.WriteLine(e);
}
return result;
}
public bool InsertDiscount(Discount discount)
{
string sql =
"insert into `discount` (`id`, `name`, `description`, `discount_percent`) values (0, @name, @description, @discount_percent)";
try
{
connection.Open();
using (var command = new MySqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@id", discount.Id);
command.Parameters.AddWithValue("@name", discount.Name);
command.Parameters.AddWithValue("@description", discount.Description);
command.Parameters.AddWithValue("@discount_percent", discount.DiscountPercent);
}
connection.Close();
}
catch (Exception e)
{
connection.Close();
return false;
}
connection.Close();
return false;
}
public bool UpdateDiscount(Discount discount)
{
string sql =
"update `discount` set name = @name, description = @description, discount_percent = @discount_percent";
try
{
connection.Open();
using (var command = new MySqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@id", discount.Id);
command.Parameters.AddWithValue("@name", discount.Name);
command.Parameters.AddWithValue("@description", discount.Description);
command.Parameters.AddWithValue("@discount_percent", discount.DiscountPercent);
}
connection.Close();
}
catch (Exception e)
{
connection.Close();
return false;
}
connection.Close();
return false;
}
public bool DeleteDiscount(Discount discount)
{
string sql = "delete from `discount` where `id` = " + discount.Id;
try
{
connection.Open();
using (var command = new MySqlCommand(sql, connection))
{
command.ExecuteNonQuery();
}
connection.Close();
}
catch (Exception e)
{
connection.Close();
return false;
}
connection.Close();
return true;
}
}