BathhouseManagment/Database/ServiceRepository.cs

117 lines
3.4 KiB
C#

using System;
using System.Collections.Generic;
using BathHouseManagmet.Models;
using Microsoft.Extensions.Options;
using MySqlConnector;
namespace BathHouseManagmet.Database;
public class ServiceRepository
{
MySqlConnection connection;
public ServiceRepository(IOptions<DatabaseConnection> connect)
{
connection = new MySqlConnection(connect.Value.ConnectionString);
}
public List<Service> GetServices()
{
List<Service> result = new();
string sql = "select * from `service`";
try
{
connection.Open();
using (var command = new MySqlCommand(sql, connection))
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
result.Add(new Service
{
Id = reader.GetInt32("id"),
Name = reader.GetString("name"),
Description = reader.GetString("description"),
Price = reader.GetInt32("price")
});
}
}
connection.Close();
}
catch (Exception e)
{
Console.WriteLine(e);
}
return result;
}
public bool InsertService(Service service)
{
string sql = "insert into `service` (`id`, `name`, `description`, `price`) values (0, @name, @description, @price)";
try
{
connection.Open();
using (var command = new MySqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@id", service.Id);
command.Parameters.AddWithValue("@name", service.Name);
command.Parameters.AddWithValue("@description", service.Description);
command.Parameters.AddWithValue("@price", service.Price);
command.ExecuteNonQuery();
}
connection.Close();
}
catch (Exception e)
{
connection.Close();
return false;
}
connection.Close();
return true;
}
public bool UpdateService(Service service)
{
string sql = "update `service` set name = @name, description = @description, price = @price";
try
{
connection.Open();
using (var command = new MySqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@name", service.Name);
command.Parameters.AddWithValue("@description", service.Description);
command.Parameters.AddWithValue("@price", service.Price);
command.ExecuteNonQuery();
}
connection.Close();
}
catch (Exception e)
{
connection.Close();
return false;
}
connection.Close();
return true;
}
public bool DeleteService(Service service)
{
string sql = "delete from `service` where `id` =" + service.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;
}
}