PIbd-23_Firsov_KA_SUBD/Hotel/HotelDatabase/Implement/GuestImplement.cs
2024-05-29 14:28:53 +04:00

99 lines
3.7 KiB
C#

using HotelAbstractions.Logic;
using HotelAbstractions.Models;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HotelDatabase.Implement
{
public class GuestImplement : IGuestLogic
{
public Guest? Create(Guest guest)
{
using var con = SqlConnection.GetConnection();
con.Open();
using var cmd = new NpgsqlCommand("INSERT INTO guest (full_name, phone_number, birth_date, passport_id, gender) VALUES (@Full_name, @Phone_number, @Birth_date, @Passport_id, @Gender)", con);
cmd.Parameters.AddWithValue("@Full_name", guest.FIO);
cmd.Parameters.AddWithValue("@Phone_number", guest.PhoneNumber);
cmd.Parameters.AddWithValue("@Birth_date", guest.BirthDate);
cmd.Parameters.AddWithValue("@Passport_id", guest.PassportId);
cmd.Parameters.AddWithValue("@Gender", guest.Gender.ToString());
cmd.ExecuteNonQuery();
return guest;
}
public Guest? Delete(int id)
{
var element = Get(id);
using var con = SqlConnection.GetConnection();
con.Open();
using var cmd = new NpgsqlCommand($"DELETE FROM guest WHERE guest_id = {id}", con);
cmd.ExecuteNonQuery();
return element;
}
public Guest? Get(int id)
{
using var con = SqlConnection.GetConnection();
con.Open();
using var cmd = new NpgsqlCommand($"SELECT * FROM guest WHERE guest_id = {id}", con);
using var reader = cmd.ExecuteReader();
if (reader.Read())
{
return new Guest
{
Id = reader.GetInt32(0),
FIO = reader.GetString(1),
PhoneNumber = reader.GetString(2),
BirthDate = ToDateOnly(reader.GetDateTime(3)),
PassportId = reader.GetString(4),
Gender = (GenderEnum)Enum.Parse(typeof(GenderEnum), reader.GetString(5)),
};
}
return null;
}
public List<Guest> GetAll()
{
var guests = new List<Guest>();
using var con = SqlConnection.GetConnection();
con.Open();
using var cmd = new NpgsqlCommand("SELECT * FROM guest order by guest_id", con);
using var reader = cmd.ExecuteReader();
while (reader.Read())
{
guests.Add(new Guest
{
Id = reader.GetInt32(0),
FIO = reader.GetString(1),
PhoneNumber = reader.GetString(2),
BirthDate = ToDateOnly(reader.GetDateTime(3)),
PassportId = reader.GetString(4),
Gender = (GenderEnum)Enum.Parse(typeof(GenderEnum), reader.GetString(5)),
});
}
return guests;
}
public Guest? Update(Guest guest)
{
using var con = SqlConnection.GetConnection();
con.Open();
using var cmd = new NpgsqlCommand($"UPDATE guest SET full_name = '{guest.FIO}', phone_number = '{guest.PhoneNumber}', birth_date = '{guest.BirthDate}', passport_id = '{guest.PassportId}', gender = '{guest.Gender}' WHERE guest_id = '{guest.Id}'", con);
cmd.ExecuteNonQuery();
var element = Get(guest.Id);
return element;
}
public DateOnly ToDateOnly (DateTime dateTime)
{
var DateTime = dateTime;
var Date = new DateOnly(DateTime.Year, DateTime.Month, DateTime.Day);
return Date;
}
}
}