104 lines
3.4 KiB
C#
104 lines
3.4 KiB
C#
using LawFirmContracts.BindingModels;
|
|
using LawFirmContracts.ViewModels;
|
|
using LawFirmDataModels.Models;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.ComponentModel.DataAnnotations;
|
|
using System.ComponentModel.DataAnnotations.Schema;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace LawFirmDatabaseImplement.Models
|
|
{
|
|
public class Law : ILawModel
|
|
{
|
|
public int Id { get; set; }
|
|
[Required]
|
|
public string LawName { get; set; } = string.Empty;
|
|
[Required]
|
|
public double Price { get; set; }
|
|
private Dictionary<int, (IComponentModel, int)>? _LawComponents =
|
|
null;
|
|
[NotMapped]
|
|
public Dictionary<int, (IComponentModel, int)> LawComponents
|
|
{
|
|
get
|
|
{
|
|
if (_LawComponents == null)
|
|
{
|
|
_LawComponents = Components
|
|
.ToDictionary(recPC => recPC.ComponentId, recPC =>
|
|
(recPC.Component as IComponentModel, recPC.Count));
|
|
}
|
|
return _LawComponents;
|
|
}
|
|
}
|
|
[ForeignKey("LawId")]
|
|
public virtual List<LawComponent> Components { get; set; } = new();
|
|
[ForeignKey("LawId")]
|
|
public virtual List<Order> Orders { get; set; } = new();
|
|
public static Law Create(LawFirmDataBase context,
|
|
LawBindingModel model)
|
|
{
|
|
return new Law()
|
|
{
|
|
Id = model.Id,
|
|
LawName = model.LawName,
|
|
Price = model.Price,
|
|
Components = model.LawComponents.Select(x => new
|
|
LawComponent
|
|
{
|
|
Component = context.Components.First(y => y.Id == x.Key),
|
|
Count = x.Value.Item2
|
|
}).ToList()
|
|
};
|
|
}
|
|
public void Update(LawBindingModel model)
|
|
{
|
|
LawName = model.LawName;
|
|
Price = model.Price;
|
|
}
|
|
public LawViewModel GetViewModel => new()
|
|
{
|
|
Id = Id,
|
|
LawName = LawName,
|
|
Price = Price,
|
|
LawComponents = LawComponents
|
|
};
|
|
public void UpdateComponents(LawFirmDataBase context,
|
|
LawBindingModel model)
|
|
{
|
|
var LawComponents = context.LawComponents.Where(rec =>
|
|
rec.LawId == model.Id).ToList();
|
|
if (LawComponents != null && LawComponents.Count > 0)
|
|
{
|
|
context.LawComponents.RemoveRange(LawComponents.Where(rec
|
|
=> !model.LawComponents.ContainsKey(rec.ComponentId)));
|
|
|
|
context.SaveChanges();
|
|
foreach (var updateComponent in LawComponents)
|
|
{
|
|
updateComponent.Count =
|
|
model.LawComponents[updateComponent.ComponentId].Item2;
|
|
model.LawComponents.Remove(updateComponent.ComponentId);
|
|
}
|
|
context.SaveChanges();
|
|
}
|
|
var Law = context.Laws.First(x => x.Id == Id);
|
|
foreach (var pc in model.LawComponents)
|
|
{
|
|
context.LawComponents.Add(new LawComponent
|
|
{
|
|
Law = Law,
|
|
Component = context.Components.First(x => x.Id == pc.Key),
|
|
Count = pc.Value.Item2
|
|
});
|
|
context.SaveChanges();
|
|
}
|
|
_LawComponents = null;
|
|
}
|
|
}
|
|
}
|
|
|