101 lines
2.6 KiB
C#
101 lines
2.6 KiB
C#
using Microsoft.EntityFrameworkCore.Metadata.Internal;
|
|
using ServiceStationContracts.BindingModels;
|
|
using ServiceStationContracts.ViewModels;
|
|
using ServiceStationDataModels.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 ServiceStationsDataBaseImplement.Models
|
|
{
|
|
public class Work : IWorkModel {
|
|
|
|
public int Id { get; set; }
|
|
|
|
[Required]
|
|
public DateTime Date { get; set; } = DateTime.Now;
|
|
|
|
[Required]
|
|
public double Price { get; set; }
|
|
|
|
[ForeignKey("ExecutorId")]
|
|
public int ExecutorId { get; set; }
|
|
|
|
[ForeignKey("TaskId")]
|
|
public int TaskId { get; set; }
|
|
|
|
|
|
[ForeignKey("WorkId")]
|
|
public virtual List<WorkClient> WorkClients { get; set; } = new();
|
|
|
|
|
|
public Dictionary<int, IClientModel>? _clientList = null;
|
|
|
|
[NotMapped]
|
|
public Dictionary<int, IClientModel> ClientList {
|
|
get {
|
|
if (_clientList == null) {
|
|
_clientList = WorkClients.ToDictionary(recWC => recWC.WorkId, recWC => recWC._client as IClientModel);
|
|
}
|
|
return _clientList;
|
|
}
|
|
}
|
|
|
|
public static Work? Create(Database context, WorkBindingModel? model) {
|
|
if (model == null) {
|
|
return null;
|
|
}
|
|
return new Work() {
|
|
Id = model.Id,
|
|
Date = model.Date,
|
|
Price = model.Price,
|
|
ExecutorId = model.ExecutorId,
|
|
TaskId = model.TaskId,
|
|
WorkClients = model.ClientList.Select(x => new WorkClient {
|
|
_work = context.Works.First(y => y.Id == x.Key)
|
|
}).ToList()
|
|
};
|
|
}
|
|
|
|
public void Update(WorkBindingModel? model) {
|
|
if (model == null) {
|
|
return;
|
|
}
|
|
Price = model.Price;
|
|
}
|
|
|
|
public WorkViewModel GetViewModel => new() {
|
|
Id = Id,
|
|
Date = Date,
|
|
Price = Price,
|
|
ExecutorId = ExecutorId,
|
|
TaskId = TaskId,
|
|
ClientList = ClientList
|
|
};
|
|
|
|
public void UpdateClients(Database context, WorkBindingModel model) {
|
|
var worckClients = context.WorksClients.Where(rec => rec.WorkId == model.Id).ToList();
|
|
if (worckClients != null && worckClients.Count > 0) {
|
|
// Нужно удалить те записи, которых нет в модели
|
|
context.WorksClients.RemoveRange(worckClients.Where(rec => !model.ClientList.ContainsKey(rec.ClientId)));
|
|
context.SaveChanges();
|
|
}
|
|
// получаем работу, добавляем новые записи
|
|
var work = context.Works.First(x => x.Id == Id);
|
|
foreach (var wc in model.ClientList) {
|
|
context.WorksClients.Add(new WorkClient {
|
|
_work = work,
|
|
_client = context.Clients.First(x => x.Id == wc.Key)
|
|
});
|
|
context.SaveChanges();
|
|
}
|
|
_clientList = null;
|
|
}
|
|
|
|
}
|
|
}
|