BathhouseManagment/Database/EmployeeRepository.cs

127 lines
4.0 KiB
C#

using System;
using System.Collections.Generic;
using BathHouseManagmet.Models;
using Microsoft.Extensions.Options;
using MySqlConnector;
namespace BathHouseManagmet.Database;
public class EmployeeRepository
{
MySqlConnection connection;
public EmployeeRepository(IOptions<DatabaseConnection> connect)
{
connection = new MySqlConnection(connect.Value.ConnectionString);
}
public List<Employee> GetEmployees()
{
List<Employee> result = new();
string sql = "select e.id as eid, e.position_id as pid, e.name as ename, e.surname as esurname, p.name as pname from employee e join position p on e.position_id = p.id";
try
{
connection.Open();
using (var command = new MySqlCommand(sql, connection))
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
result.Add(new Employee
{
/*
Id = reader.GetInt32("id"),
Name = reader.GetString("name"),
Surname = reader.GetString("surname"),
PositionId = reader.GetInt32("position_id"),
*/
Id = reader.GetInt32("eid"),
Name = reader.GetString("ename"),
Surname = reader.GetString("esurname"),
Position = new Position()
{
Id = reader.GetInt32("pid"),
Name = reader.GetString("name"),
}
});
}
}
connection.Close();
}
catch (Exception e)
{
Console.WriteLine(e);
}
return result;
}
public bool InsertEmployee(Employee employee)
{
string sql =
"insert into `employee` (`id`, `name`, `surname`, `on_work`, `position_id`) values (0, @name, @surname, @on_work, @position_id)";
try
{
connection.Open();
using (var command = new MySqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@name", employee.Name);
command.Parameters.AddWithValue("@surname", employee.Surname);
command.Parameters.AddWithValue("@position_id", employee.PositionId);
command.ExecuteNonQuery();
}
connection.Close();
}
catch (Exception e)
{
connection.Close();
return false;
}
connection.Close();
return true;
}
public bool UpdateEmployee(Employee employee)
{
string sql = "update `employee` set name = @name, surname = @surname, on_work = @on_work, position_id = @position_id";
try
{
connection.Open();
using (var command = new MySqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@name", employee.Name);
command.Parameters.AddWithValue("@surname", employee.Surname);
command.Parameters.AddWithValue("@position_id", employee.PositionId);
command.ExecuteNonQuery();
}
connection.Close();
}
catch (Exception e)
{
connection.Close();
return false;
}
connection.Close();
return true;
}
public bool DeleteEmployee(Employee employee)
{
string sql = "delete from `employee` where `id` = " + employee.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;
}
}