101 lines
2.7 KiB
C#
101 lines
2.7 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;
|
|
|
|
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; }
|
|
|
|
public int ExecutorId { get; set; }
|
|
|
|
public int TaskByWorkId { get; set; }
|
|
|
|
[ForeignKey("TaskByWorkId")]
|
|
public virtual TaskByWork? _task { 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.ClientId, 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,
|
|
TaskByWorkId = model.TaskByWorkId,
|
|
WorkClients = model.ClientList.Select(x => new WorkClient {
|
|
_client = context.Clients.First(y => y.Id == x.Key),
|
|
PointCount = 0
|
|
}).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,
|
|
TaskByWorkId = TaskByWorkId,
|
|
ClientList = ClientList,
|
|
TaskName = _task?.Name ?? string.Empty,
|
|
};
|
|
|
|
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);
|
|
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;
|
|
}
|
|
}
|
|
}
|