PIbd-22_Chernyshev_G.J._30_.../GarmentFactoryDatabaseImplement/Models/Textile.cs

108 lines
3.8 KiB
C#
Raw Normal View History

2024-03-20 10:21:07 +04:00
using GarmentFactoryContracts.BindingModels;
using GarmentFactoryContracts.ViewModels;
using GarmentFactoryDataModels.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 GarmentFactoryDatabaseImplement.Models
{
public class Textile : ITextileModel
{
public int Id { get; set; }
[Required]
public string TextileName { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
private Dictionary<int, (IComponentModel, int)>? _textileComponents = null;
[NotMapped]
public Dictionary<int, (IComponentModel, int)> TextileComponents
{
get
{
if (_textileComponents == null)
{
_textileComponents = Components
.ToDictionary(recPC => recPC.ComponentId, recPC =>
(recPC.Component as IComponentModel, recPC.Count));
}
return _textileComponents;
}
}
[ForeignKey("TextileId")]
public virtual List<TextileComponent> Components { get; set; } = new();
[ForeignKey("TextileId")]
public virtual List<Order> Orders { get; set; } = new();
public static Textile Create(GarmentFactoryDatabase context, TextileBindingModel model)
{
return new Textile()
{
Id = model.Id,
TextileName = model.TextileName,
Price = model.Price,
Components = model.TextileComponents.Select(x => new TextileComponent
{
Component = context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(TextileBindingModel model)
{
TextileName = model.TextileName;
Price = model.Price;
}
public TextileViewModel GetViewModel => new()
{
Id = Id,
TextileName = TextileName,
Price = Price,
TextileComponents = TextileComponents
};
public void UpdateComponents(GarmentFactoryDatabase context, TextileBindingModel model)
{
var textileComponents = context.TextileComponents.Where(rec =>rec.TextileId == model.Id).ToList();
if (textileComponents != null && textileComponents.Count > 0)
{
// удалили те, которых нет в модели
context.TextileComponents.RemoveRange(textileComponents.Where(rec => !model.TextileComponents.ContainsKey(rec.ComponentId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateComponent in textileComponents)
{
updateComponent.Count =
model.TextileComponents[updateComponent.ComponentId].Item2;
model.TextileComponents.Remove(updateComponent.ComponentId);
}
context.SaveChanges();
}
var textile = context.Textiles.First(x => x.Id == Id);
foreach (var pc in model.TextileComponents)
{
context.TextileComponents.Add(new TextileComponent
{
Textile = textile,
Component = context.Components.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_textileComponents = null;
}
}
}