107 lines
3.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using RouteGuideContracts.BindingModels;
using RouteGuideContracts.ViewModels;
using RouteGuideDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RouteGuideDatabaseImplements.Models
{
public class Route : IRouteModel
{
public int Id { get; private set; }
[Required]
public string Name { get; private set; } = string.Empty;
Dictionary<int, (IStopModel, int)>? _routeStops = null;
[NotMapped]
public Dictionary<int, (IStopModel, int)> RouteStops
{
get
{
if (_routeStops == null)
{
_routeStops = Stops.ToDictionary(recPC => recPC.StopId, recPC => (recPC.Stop as IStopModel, recPC.Number));
}
return _routeStops;
}
}
[ForeignKey("RouteId")]
public virtual List<RouteStop> Stops { get; set; } = new();
public static Route Create(RouteGuideDatabase context, RouteBindingModel model)
{
return new Route()
{
Id = model.Id,
Name = model.Name,
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)
{
Name = model.Name;
}
public RouteViewModel GetViewModel
{
get
{
using var context = new RouteGuideDatabase();
return new RouteViewModel
{
Id = Id,
Name = Name,
RouteStops = RouteStops
};
}
}
public void UpdateStops(RouteGuideDatabase context, RouteBindingModel model)
{
var routeStops = context.RoutesStops.Where(rec => rec.RouteId == model.Id).ToList();
if (routeStops != null && routeStops.Count > 0)
{ // удалили те, которых нет в модели
context.RoutesStops.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 pc in model.RouteStops)
{
context.RoutesStops.Add(new RouteStop
{
Route = route,
Stop = context.Stops.First(x => x.Id == pc.Key),
Number = pc.Value.Item2
});
context.SaveChanges();
}
_routeStops = null;
}
}
}