SUBD_Labs/BeautySalonDatabaseImplement/Models/Master.cs

93 lines
3.5 KiB
C#
Raw Normal View History

using BeautySalonContracts.BindingModels;
using BeautySalonContracts.ViewModels;
using BeautySalonDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace BeautySalonDatabaseImplement.Models
{
public class Master : IMasterModel
{
public int Id { get; private set; }
[Required]
public string MasterFIO { get; set; } = string.Empty;
[Required]
2023-05-13 19:29:18 +04:00
public double WorkingHours { get; set; }
private Dictionary<int, (IServiceModel, int)>? _masterServices = null;
[NotMapped]
public Dictionary<int, (IServiceModel, int)> MasterServices
{
get
{
if (_masterServices == null)
{
_masterServices = Services
.ToDictionary(recPC => recPC.MasterId, recPC =>
(recPC.Service as IServiceModel, recPC.Count));
}
return _masterServices;
}
}
[ForeignKey("MasterId")]
public virtual List<MasterService> Services { get; set; } = new();
[ForeignKey("MasterId")]
public virtual List<Visit> Visits { get; set; } = new();
public static Master Create(BeautySalonDatabase context, MasterBindingModel model)
{
return new Master
{
Id = model.Id,
MasterFIO = model.MasterFIO,
2023-05-13 19:29:18 +04:00
WorkingHours = model.WorkingHours,
Services = model.MasterServices.Select(x => new MasterService
{
Service = context.Services.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(MasterBindingModel model)
{
MasterFIO = model.MasterFIO;
2023-05-13 19:29:18 +04:00
WorkingHours = model.WorkingHours;
}
public MasterViewModel GetViewModel => new()
{
Id = Id,
MasterFIO = MasterFIO,
2023-05-13 19:29:18 +04:00
WorkingHours = WorkingHours,
MasterServices = MasterServices
};
public void UpdateServices(BeautySalonDatabase context, MasterBindingModel model)
{
var masterServices = context.MasterServices.Where(rec => rec.MasterId == model.Id).ToList();
if (masterServices != null && masterServices.Count > 0)
{ // удалили те, которых нет в модели
context.MasterServices.RemoveRange(masterServices.Where(rec
=> !model.MasterServices.ContainsKey(rec.ServiceId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateService in masterServices)
{
updateService.Count =
model.MasterServices[updateService.ServiceId].Item2;
model.MasterServices.Remove(updateService.ServiceId);
}
context.SaveChanges();
}
var master = context.Masters.First(x => x.Id == Id);
foreach (var pc in model.MasterServices)
{
context.MasterServices.Add(new MasterService
{
Master = master,
Service = context.Services.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_masterServices = null;
}
}
}