PIbd-23_Starostin_I.K._Cour.../STODataBaseImplement/TechnicalWork.cs

115 lines
3.8 KiB
C#

using STOContracts.BindingModels;
using STOContracts.ViewModels;
using STODatabaseImplement;
using STODataModels;
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 DatabaseImplement
{
public class TechnicalWork: ITechnicalWorkModel
{
public int Id { get; private set; }
[Required]
public string Name { get; private set; } = string.Empty;
public string Description { get; private set; } = string.Empty;
[Required]
public DateTime Date { get; private set; } = DateTime.MinValue;
public Dictionary<int, (IWorkModel, int)> _Works = null;
[NotMapped]
public Dictionary<int, (IWorkModel, int)> TechnicalworkWorks
{
get
{
if (_Works == null)
{
_Works = Works
.ToDictionary(recPC => recPC.Id, recPC =>
(recPC.Work as IWorkModel, recPC.Count));
}
return _Works;
}
}
[ForeignKey("TechnicalWorkId")]
public virtual List<WorkTechnicalWork> Works { get; set; } = new();
public static TechnicalWork? Create(STODatabase context, TechnicalWorkBindingModel model)
{
if (model == null)
{
return null;
}
return new TechnicalWork()
{
Id = model.Id,
Name = model.Name,
Description = model.Description,
Date = model.Date,
Works = model.TechnicalworkWorks.Select(x => new
WorkTechnicalWork
{
Work = context.Works.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(TechnicalWorkBindingModel model)
{
if (model == null)
{
return;
}
Id = model.Id;
Name = model.Name;
Description = model.Description;
Date = model.Date;
}
public TechnicalWorkViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Description = Description,
Date = Date
};
public void UpdateWorks(STODatabase context, TechnicalWorkBindingModel model)
{
var works = context.WorkTechnicalWork.Where(rec =>
rec.TechnicalWorkId == model.Id).ToList();
if (works != null && TechnicalworkWorks.Count > 0)
{
context.WorkTechnicalWork.RemoveRange(works.Where(rec
=> !model.TechnicalworkWorks.ContainsKey(rec.WorkId)));
context.SaveChanges();
foreach (var updateComponent in works)
{
updateComponent.Count =
model.TechnicalworkWorks[updateComponent.WorkId].Item2;
model.TechnicalworkWorks.Remove(updateComponent.WorkId);
}
context.SaveChanges();
}
var manufacture = context.TechnicalWorks.First(x => x.Id == Id);
foreach (var pc in model.TechnicalworkWorks)
{
context.WorkTechnicalWork.Add(new WorkTechnicalWork
{
TechnicalWork = manufacture,
Work = context.Works.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_Works = null;
}
}
}