PIbd-42_Kashin_M.I_CPO_Cour.../Model/DataWorker.cs

81 lines
2.7 KiB
C#

using EmployeeManager.Model;
using EmployeeManager.Model.Data;
using System.Data.Common;
using System.Linq;
public interface IPhysicalPersonService
{
List<PhysicalPerson> GetAllPhysicalPersons();
string CreatePhysicalPerson(PhysicalPersonDto personDto);
string EditPhysicalPerson(int id, PhysicalPersonDto updatedData);
string DeletePhysicalPerson(int id);
}
public class PhysicalPersonService : IPhysicalPersonService
{
private readonly ApplicationConext _context;
public PhysicalPersonService(ApplicationConext context)
{
_context = context;
}
public List<PhysicalPerson> GetAllPhysicalPersons() => _context.PhysicalPersons.ToList();
public string CreatePhysicalPerson(PhysicalPersonDto personDto)
{
if (_context.PhysicalPersons.Any(p =>
p.NamePhysicalPersons == personDto.Name &&
p.SurnamePhysicalPersons == personDto.Surname &&
p.Birthday == personDto.Birthday))
{
return "Физическое лицо уже существует.";
}
var newPerson = new PhysicalPerson
{
NamePhysicalPersons = personDto.Name,
SurnamePhysicalPersons = personDto.Surname,
PatronomicPhysicalPersons = personDto.Patronomic,
Birthday = personDto.Birthday,
Gender = personDto.Gender,
Address = personDto.Address,
Telephone = personDto.Telephone
};
_context.PhysicalPersons.Add(newPerson);
_context.SaveChanges();
return "Физическое лицо добавлено.";
}
public string EditPhysicalPerson(int id, PhysicalPersonDto updatedData)
{
var person = _context.PhysicalPersons.FirstOrDefault(p => p.Id == id);
if (person == null)
return "Физическое лицо не найдено.";
person.NamePhysicalPersons = updatedData.Name;
person.SurnamePhysicalPersons = updatedData.Surname;
person.PatronomicPhysicalPersons = updatedData.Patronomic;
person.Birthday = updatedData.Birthday;
person.Gender = updatedData.Gender;
person.Address = updatedData.Address;
person.Telephone = updatedData.Telephone;
_context.SaveChanges();
return "Данные физического лица обновлены.";
}
public string DeletePhysicalPerson(int id)
{
var person = _context.PhysicalPersons.FirstOrDefault(p => p.Id == id);
if (person == null)
return "Физическое лицо не найдено.";
_context.PhysicalPersons.Remove(person);
_context.SaveChanges();
return "Физическое лицо удалено.";
}
}