BathhouseManagment/Models/Database/ServiceRepository.cs

127 lines
3.6 KiB
C#

using System;
using System.Collections.Generic;
using BathHouseManagmet.Models;
using BathHouseManagmet.Models.Database;
using Microsoft.Extensions.Options;
using MySqlConnector;
namespace BathHouseManagmet.Database;
public class ServiceRepository : BaseRepository<Service>, IDisposable
{
public ServiceRepository()
{
OpenConnection();
}
public override List<Service> GetPage(int pageNumber, int pageSize)
{
List<Service> result = new();
string sql = "select * from `service` limit @limit offset @offset";
try
{
using var command = new MySqlCommand(sql, connection);
command.Parameters.AddWithValue("@limit", pageNumber);
command.Parameters.AddWithValue("@offset", pageNumber * pageSize);
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")
});
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
return result;
}
public override bool Add(Service service)
{
string sql = "insert into `service` (`id`, `name`, `description`, `price`) values (0, @name, @description, @price)";
try
{
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();
}
}
catch (Exception e)
{
Console.WriteLine(e);
return false;
}
return true;
}
public override bool Update(Service service)
{
string sql = "update `service` set name = @name, description = @description, price = @price";
try
{
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();
}
}
catch (Exception e)
{
Console.WriteLine(e);
return false;
}
return true;
}
public override bool Delete(Service service)
{
string sql = "delete from `service` where `id` =" + service.Id;
try
{
using (var command = new MySqlCommand(sql, connection))
{
command.ExecuteNonQuery();
}
}
catch (Exception e)
{
Console.WriteLine(e);
return false;
}
return true;
}
public int GetRowsCount()
{
string sql = "select count(id) from `service`";
try
{
using var mc = new MySqlCommand(sql, connection);
return Convert.ToInt32(mc.ExecuteScalar());
}
catch (Exception e)
{
Console.WriteLine(e);
return 0;
}
}
public void Dispose()
{
CloseConnection();
base.Dispose();
}
}