PIbd23_Ivanova_Yakobchuk_Co.../LawCompany/LawCompanyDatabaseImplement/Models/Hearing.cs

99 lines
3.4 KiB
C#
Raw Normal View History

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;
2024-05-01 17:18:02 +04:00
namespace LawCompanyDatabaseImplement.Models
{
public class Hearing : IHearingModel
2024-05-01 17:18:02 +04:00
{
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;
[NotMapped]
public Dictionary<int, ILawyerModel> HearingLawyers
{
get
{
if (_hearingLawyers == null)
{
using var context = new LawCompanyDatabase();
_hearingLawyers = Lawyers
.ToDictionary(x => x.LawyerId, x => (context.Lawyers
.FirstOrDefault(y => y.Id == x.LawyerId) as ILawyerModel));
}
return _hearingLawyers;
}
}
[ForeignKey("HearingId")]
public virtual List<HearingLawyer> Lawyers { get; set; } = new();
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,
HearingLawyers = HearingLawyers
};
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();
}
var _hearing = context.Hearings.First(x => x.Id == Id);
foreach (var pc in model.HearingLawyers)
{
if (!HearingLawyers.ContainsKey(pc.Key))
{
context.HearingLawyers.Add(new HearingLawyer
{
Hearing = _hearing,
Lawyer = context.Lawyers.First(x => x.Id == pc.Key),
});
}
context.SaveChanges();
}
_hearingLawyers = null;
}
2024-05-01 17:18:02 +04:00
}
}