using RouteGuideContracts.BindingModels;
using RouteGuideContracts.ViewModels;
using RouteGuideDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace RouteGuideDatabaseImplement.Models
{
///
/// Сущность "Маршрут"
///
public class Route : IRouteModel
{
///
/// Идентификатор
///
public int Id { get; private set; }
///
/// Название маршрута
///
[Required]
public string Name { get; private set; } = string.Empty;
///
/// Идентификатор транспорта
///
[ForeignKey("TransportId")]
public int TransportId { get; private set; }
///
/// Сущность "Транспорт"
///
public virtual Transport Transport { get; private set; } = new();
///
/// Коллекция остановок маршрута
///
private Dictionary? _routeStops = null;
///
/// Коллекция остановок маршрута
///
[NotMapped]
public Dictionary RouteStops
{
get
{
if (_routeStops == null)
{
_routeStops = Stops
.ToDictionary(recRS => recRS.StopId, recRS => (recRS.Stop as IStopModel, recRS.Number));
}
return _routeStops;
}
}
///
/// Связь с классом связи маршрутов и остановок
///
[ForeignKey("RouteId")]
public virtual List Stops { get; set; } = new();
///
/// Созданме модели
///
///
///
///
public static Route Create(RouteGuideDatabase context, RouteBindingModel model)
{
return new Route()
{
Id = model.Id,
Name = model.Name,
TransportId = model.TransportId,
Transport = context.Transport
.FirstOrDefault(x => x.Id == model.TransportId),
Stops = model.RouteStops.Select(x => new RouteStop
{
Stop = context.Stops.First(y => y.Id == x.Key),
Number = x.Value.Item2
}).ToList()
};
}
///
/// Изменение модели
///
///
public void Update(RouteBindingModel model)
{
if (model == null)
{
return;
}
Name = model.Name;
}
///
/// Получение модели
///
public RouteViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
TransportId = TransportId,
RouteStops = RouteStops,
TransportLicense = Transport.License
};
///
/// Обновление списка связей
///
///
///
public void UpdateStops(RouteGuideDatabase context, RouteBindingModel model)
{
var routeStops = context.RouteStops.Where(rec => rec.RouteId == model.Id).ToList();
if (routeStops != null && routeStops.Count > 0)
{
// Удаление остановок, которых нет в маршруте
context.RouteStops.RemoveRange(routeStops.Where(rec => !model.RouteStops.ContainsKey(rec.StopId)));
context.SaveChanges();
// Обновление количества у существующих записей
foreach (var updateStop in routeStops)
{
updateStop.Number = model.RouteStops[updateStop.StopId].Item2;
model.RouteStops.Remove(updateStop.StopId);
}
context.SaveChanges();
}
var route = context.Routes.First(x => x.Id == Id);
foreach (var rs in model.RouteStops)
{
context.RouteStops.Add(new RouteStop
{
Route = route,
Stop = context.Stops.First(x => x.Id == rs.Key),
Number = rs.Value.Item2
});
context.SaveChanges();
}
_routeStops = null;
}
}
}