PIbd23_Ivanova_Yakobchuk_Co.../LawCompany/LawCompanyDatabaseImplement/Models/Case.cs

111 lines
2.8 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 LawCompanyDataModels.Enums;
using LawCompanyDataModels.Models;
using LawCompanyContracts.BindingModels;
using LawCompanyContracts.ViewModels;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace LawCompanyDatabaseImplement.Models
{
public class Case : ICaseModel
{
public int Id { get; private set; }
[Required]
public string Name { get; private set; } = String.Empty;
[Required]
public DateTime DateCreate { get; private set; }
public DateTime? DateImplement { get; private set; }
[Required]
public CaseStatus Status { get; private set; }
private Dictionary<int, IClientModel>? _caseClients = null;
public int ExecutorId { get; set; }
[NotMapped]
public Dictionary<int, IClientModel> CaseClients
{
get
{
if (_caseClients == null)
{
_caseClients = Clients.ToDictionary(x => x.ClientId, x => (x.Client as IClientModel));
}
return _caseClients;
}
}
[ForeignKey("CaseId")]
public virtual List<CaseClient> Clients { get; set; } = new();
public static Case Create(LawCompanyDatabase context, CaseBindingModel model)
{
return new Case()
{
Id = model.Id,
Name = model.Name,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
Status = model.Status,
ExecutorId = model.ExecutorId,
Clients = model.CaseClients.Select(x => new CaseClient
{
Client = context.Clients.First(y => y.Id == x.Key)
}).ToList()
};
}
public void Update(CaseBindingModel model)
{
if (model.Status == CaseStatus.ЗакрытиеДела)
{
DateImplement = DateTime.Now;
}
Name = model.Name;
Status = model.Status;
if (model.DateImplement.HasValue)
{
DateImplement = model.DateImplement;
}
}
public CaseViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
DateCreate = DateCreate,
DateImplement = DateImplement,
ExecutorId = ExecutorId,
Status = Status,
};
public void UpdateClients(LawCompanyDatabase context, CaseBindingModel model)
{
var caseClients = context.CaseClients.Where(rec => rec.CaseId == model.Id).ToList();
if (caseClients != null && caseClients.Count > 0)
{ // удалили те, которых нет в модели
context.CaseClients.RemoveRange(caseClients.Where(rec => !model.CaseClients.ContainsKey(rec.ClientId)));
context.SaveChanges();
foreach (var updateLunch in caseClients)
{
model.CaseClients.Remove(updateLunch.ClientId);
}
context.SaveChanges();
}
var _case = context.Cases.First(x => x.Id == Id);
foreach (var pc in model.CaseClients)
{
context.CaseClients.Add(new CaseClient
{
Case = _case,
Client = context.Clients.First(x => x.Id == pc.Key),
});
context.SaveChanges();
}
_caseClients = null;
}
}
}