SUBD_Labs/BeautySalonDatabaseImplement/Models/Master.cs

93 lines
3.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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]
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,
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;
WorkingHours = model.WorkingHours;
}
public MasterViewModel GetViewModel => new()
{
Id = Id,
MasterFIO = MasterFIO,
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;
}
}
}