PIbd23_Ivanova_Yakobchuk_Co.../LawCompany/LawCompanyDatabaseImplement/Models/Hearing.cs
2024-08-28 03:10:45 +04:00

98 lines
3.2 KiB
C#

using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.Design;
using LawCompanyContracts.BindingModels;
using LawCompanyContracts.ViewModels;
using LawCompanyDataModels.Models;
using LawCompanyDataModels.Enums;
namespace LawCompanyDatabaseImplement.Models
{
public class Hearing : IHearingModel
{
public int Id { get; private set; }
[Required]
public DateTime HearingDate { get; private set; }
[Required]
public string Judge { get; private set; } = string.Empty;
public int GuarantorId { get; set; }
private Dictionary<int, ILawyerModel> _hearingLawyers = null;
[ForeignKey("HearingId")]
public virtual List<HearingLawyer> Lawyers { get; set; } = new();
[NotMapped]
public Dictionary<int, ILawyerModel> HearingLawyers
{
get
{
if (_hearingLawyers == null)
{
_hearingLawyers = Lawyers.ToDictionary(x => x.LawyerId, x => (x.Lawyer as ILawyerModel));
}
return _hearingLawyers;
}
}
public static Hearing? Create(LawCompanyDatabase context, HearingBindingModel? model)
{
if (model == null)
{
return null;
}
return new Hearing()
{
Id = model.Id,
HearingDate = model.HearingDate,
Judge = model.Judge,
GuarantorId = model.GuarantorId,
Lawyers = model.HearingLawyers.Select(x => new HearingLawyer
{
Lawyer = context.Lawyers.First(y => y.Id == x.Key)
}).ToList()
};
}
public void Update(HearingBindingModel? model)
{
if (model == null)
{
return;
}
HearingDate = model.HearingDate;
Judge = model.Judge;
}
public HearingViewModel GetViewModel => new()
{
Id = Id,
HearingDate = HearingDate,
Judge = Judge,
GuarantorId = GuarantorId
};
public void UpdateLawyers(LawCompanyDatabase context, HearingBindingModel model)
{
var hearingLawyer = context.HearingLawyers.Where(rec => rec.HearingId == model.Id).ToList();
if (hearingLawyer != null && hearingLawyer.Count > 0)
{
context.HearingLawyers.RemoveRange(hearingLawyer.Where(rec => !model.HearingLawyers.ContainsKey(rec.LawyerId)));
context.SaveChanges();
foreach (var updateMember in hearingLawyer)
{
model.HearingLawyers.Remove(updateMember.LawyerId);
}
context.SaveChanges();
}
var _hearing = context.Hearings.First(x => x.Id == Id);
foreach (var pc in model.HearingLawyers)
{
context.HearingLawyers.Add(new HearingLawyer
{
Hearing = _hearing,
Lawyer = context.Lawyers.First(x => x.Id == pc.Key),
});
context.SaveChanges();
}
_hearingLawyers = null;
}
}
}