DatabaseImplement WIP

This commit is contained in:
parent 69d19cb676
commit 15c9409f76
19 changed files with 1414 additions and 5 deletions

View File

@ -5,9 +5,11 @@ VisualStudioVersion = 17.8.34525.116
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RouteGuideView", "RouteGuideView\RouteGuideView.csproj", "{4116AC9B-4035-4701-9C35-049AA6A83B96}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RouteGuideDataModels", "RouteGuideDataModels\RouteGuideDataModels.csproj", "{734B62E6-F4F0-4356-A4BC-067F52416282}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RouteGuideDataModels", "RouteGuideDataModels\RouteGuideDataModels.csproj", "{734B62E6-F4F0-4356-A4BC-067F52416282}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RouteGuideContracts", "RouteGuideContracts\RouteGuideContracts.csproj", "{895094AD-E3AC-4E1F-83DC-283E65EB072F}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RouteGuideContracts", "RouteGuideContracts\RouteGuideContracts.csproj", "{895094AD-E3AC-4E1F-83DC-283E65EB072F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RouteGuideDatabaseImplement", "RouteGuideDatabaseImplement\RouteGuideDatabaseImplement.csproj", "{5C2BBCAA-01A8-4B4C-B296-E7CF8DFBA884}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -27,6 +29,10 @@ Global
{895094AD-E3AC-4E1F-83DC-283E65EB072F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{895094AD-E3AC-4E1F-83DC-283E65EB072F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{895094AD-E3AC-4E1F-83DC-283E65EB072F}.Release|Any CPU.Build.0 = Release|Any CPU
{5C2BBCAA-01A8-4B4C-B296-E7CF8DFBA884}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5C2BBCAA-01A8-4B4C-B296-E7CF8DFBA884}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5C2BBCAA-01A8-4B4C-B296-E7CF8DFBA884}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5C2BBCAA-01A8-4B4C-B296-E7CF8DFBA884}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -0,0 +1,7 @@
namespace RouteGuideBusinessLogics
{
public class Class1
{
}
}

View File

@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@ -39,7 +39,7 @@ namespace RouteGuideContracts.StoragesContracts
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
TransportViewModel? Insert(RouteBindingModel model);
RouteViewModel? Insert(RouteBindingModel model);
/// <summary>
/// Редактирование элемента

View File

@ -32,7 +32,7 @@ namespace RouteGuideContracts.StoragesContracts
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
ScheduleViewModel? GetElement(ScheduleBindingModel model);
ScheduleViewModel? GetElement(ScheduleSearchModel model);
/// <summary>
/// Добавление элемента

View File

@ -39,7 +39,7 @@ namespace RouteGuideContracts.StoragesContracts
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
DriverViewModel? Insert(TransportBindingModel model);
TransportViewModel? Insert(TransportBindingModel model);
/// <summary>
/// Редактирование элемента

View File

@ -0,0 +1,125 @@
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.SearchModels;
using RouteGuideContracts.StoragesContracts;
using RouteGuideContracts.ViewModels;
using RouteGuideDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RouteGuideDatabaseImplement.Implements
{
/// <summary>
/// Хранилище для сущности "Водитель"
/// </summary>
public class DriverStorage : IDriverStorage
{
/// <summary>
/// Получение полного списка
/// </summary>
/// <returns></returns>
public List<DriverViewModel> GetFullList()
{
using var context = new RouteGuideDatabase();
return context.Drivers
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение фильтрованного списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<DriverViewModel> GetFilteredList(DriverSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new RouteGuideDatabase();
return context.Drivers
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DriverViewModel? GetElement(DriverSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new RouteGuideDatabase();
return context.Drivers
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
/// <summary>
/// Добавление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DriverViewModel? Insert(DriverBindingModel model)
{
var newDriver = Driver.Create(model);
if (newDriver == null)
{
return null;
}
using var context = new RouteGuideDatabase();
context.Drivers.Add(newDriver);
context.SaveChanges();
return newDriver.GetViewModel;
}
/// <summary>
/// Редактирование элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DriverViewModel? Update(DriverBindingModel model)
{
using var context = new RouteGuideDatabase();
var driver = context.Drivers.FirstOrDefault(x => x.Id == model.Id);
if (driver == null)
{
return null;
}
driver.Update(model);
context.SaveChanges();
return driver.GetViewModel;
}
/// <summary>
/// Удаление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DriverViewModel? Delete(DriverBindingModel model)
{
using var context = new RouteGuideDatabase();
var driver = context.Drivers.FirstOrDefault(x => x.Id == model.Id);
if (driver == null)
{
return null;
}
context.Drivers.Remove(driver);
context.SaveChanges();
return driver.GetViewModel;
}
}
}

View File

@ -0,0 +1,150 @@
using Microsoft.EntityFrameworkCore;
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.SearchModels;
using RouteGuideContracts.StoragesContracts;
using RouteGuideContracts.ViewModels;
using RouteGuideDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RouteGuideDatabaseImplement.Implements
{
/// <summary>
/// Хранилище для сущности "Маршрут"
/// </summary>
public class RouteStorage : IRouteStorage
{
/// <summary>
/// Получение полного списка
/// </summary>
/// <returns></returns>
public List<RouteViewModel> GetFullList()
{
using var context = new RouteGuideDatabase();
return context.Routes
.Include(x => x.Transport)
.Include(x => x.Stops)
.ThenInclude(x => x.Stop)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение фильтрованного списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<RouteViewModel> GetFilteredList(RouteSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new RouteGuideDatabase();
return context.Routes
.Include(x => x.Transport)
.Include(x => x.Stops)
.ThenInclude(x => x.Stop)
.ToList()
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public RouteViewModel? GetElement(RouteSearchModel model)
{
if (!model.Id.HasValue && string.IsNullOrEmpty(model.Name))
{
return null;
}
using var context = new RouteGuideDatabase();
return context.Routes
.Include(x => x.Transport)
.Include(x => x.Stops)
.ThenInclude(x => x.Stop)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name.Contains(model.Name)) || (model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
/// <summary>
/// Добавление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public RouteViewModel? Insert(RouteBindingModel model)
{
using var context = new RouteGuideDatabase();
var newRoute = Route.Create(context, model);
if (newRoute == null)
{
return null;
}
context.Routes.Add(newRoute);
context.SaveChanges();
return newRoute.GetViewModel;
}
/// <summary>
/// Редактирование элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public RouteViewModel? Update(RouteBindingModel model)
{
using var context = new RouteGuideDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var route = context.Routes.FirstOrDefault(x => x.Id == model.Id);
if (route == null)
{
return null;
}
route.Update(model);
context.SaveChanges();
route.UpdateStops(context, model);
transaction.Commit();
return route.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
/// <summary>
/// Удаление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public RouteViewModel? Delete(RouteBindingModel model)
{
using var context = new RouteGuideDatabase();
var route = context.Routes
.Include(x => x.Stops)
.FirstOrDefault(rec => rec.Id == model.Id);
if (route == null)
{
return null;
}
context.Routes.Remove(route);
context.SaveChanges();
return route.GetViewModel;
}
}
}

View File

@ -0,0 +1,129 @@
using Microsoft.EntityFrameworkCore;
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.SearchModels;
using RouteGuideContracts.StoragesContracts;
using RouteGuideContracts.ViewModels;
using RouteGuideDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RouteGuideDatabaseImplement.Implements
{
/// <summary>
/// Хранилище для сущности "Расписание"
/// </summary>
public class ScheduleStorage : IScheduleStorage
{
/// <summary>
/// Получение полного списка
/// </summary>
/// <returns></returns>
public List<ScheduleViewModel> GetFullList()
{
using var context = new RouteGuideDatabase();
return context.Schedules
.Include(x => x.Route)
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение фильтрованного списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<ScheduleViewModel> GetFilteredList(ScheduleSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new RouteGuideDatabase();
return context.Schedules
.Include(x => x.Route)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ScheduleViewModel? GetElement(ScheduleSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new RouteGuideDatabase();
return context.Schedules
.Include(x => x.Route)
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
/// <summary>
/// Добавление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ScheduleViewModel? Insert(ScheduleBindingModel model)
{
using var context = new RouteGuideDatabase();
var newSchedule = Schedule.Create(context, model);
if (newSchedule == null)
{
return null;
}
context.Schedules.Add(newSchedule);
context.SaveChanges();
return newSchedule.GetViewModel;
}
/// <summary>
/// Редактирование элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ScheduleViewModel? Update(ScheduleBindingModel model)
{
using var context = new RouteGuideDatabase();
var schedule = context.Schedules.FirstOrDefault(x => x.Id == model.Id);
if (schedule == null)
{
return null;
}
schedule.Update(model);
context.SaveChanges();
return schedule.GetViewModel;
}
/// <summary>
/// Удаление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ScheduleViewModel? Delete(ScheduleBindingModel model)
{
using var context = new RouteGuideDatabase();
var schedule = context.Schedules.FirstOrDefault(x => x.Id == model.Id);
if (schedule == null)
{
return null;
}
context.Schedules.Remove(schedule);
context.SaveChanges();
return schedule.GetViewModel;
}
}
}

View File

@ -0,0 +1,125 @@
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.SearchModels;
using RouteGuideContracts.StoragesContracts;
using RouteGuideContracts.ViewModels;
using RouteGuideDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RouteGuideDatabaseImplement.Implements
{
/// <summary>
/// Хранилище для сущности "Остановка"
/// </summary>
public class StopStorage : IStopStorage
{
/// <summary>
/// Получение полного списка
/// </summary>
/// <returns></returns>
public List<StopViewModel> GetFullList()
{
using var context = new RouteGuideDatabase();
return context.Stops
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение фильтрованного списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<StopViewModel> GetFilteredList(StopSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new RouteGuideDatabase();
return context.Stops
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public StopViewModel? GetElement(StopSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new RouteGuideDatabase();
return context.Stops
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
/// <summary>
/// Добавление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public StopViewModel? Insert(StopBindingModel model)
{
var newStop = Stop.Create(model);
if (newStop == null)
{
return null;
}
using var context = new RouteGuideDatabase();
context.Stops.Add(newStop);
context.SaveChanges();
return newStop.GetViewModel;
}
/// <summary>
/// Редактирование элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public StopViewModel? Update(StopBindingModel model)
{
using var context = new RouteGuideDatabase();
var stop = context.Stops.FirstOrDefault(x => x.Id == model.Id);
if (stop == null)
{
return null;
}
stop.Update(model);
context.SaveChanges();
return stop.GetViewModel;
}
/// <summary>
/// Удаление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public StopViewModel? Delete(StopBindingModel model)
{
using var context = new RouteGuideDatabase();
var stop = context.Stops.FirstOrDefault(x => x.Id == model.Id);
if (stop == null)
{
return null;
}
context.Stops.Remove(stop);
context.SaveChanges();
return stop.GetViewModel;
}
}
}

View File

@ -0,0 +1,129 @@
using Microsoft.EntityFrameworkCore;
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.SearchModels;
using RouteGuideContracts.StoragesContracts;
using RouteGuideContracts.ViewModels;
using RouteGuideDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RouteGuideDatabaseImplement.Implements
{
/// <summary>
/// Хранилище для сущности "Транспорт"
/// </summary>
public class TransportStorage : ITransportStorage
{
/// <summary>
/// Получение полного списка
/// </summary>
/// <returns></returns>
public List<TransportViewModel> GetFullList()
{
using var context = new RouteGuideDatabase();
return context.Transport
.Include(x => x.Driver)
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение фильтрованного списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<TransportViewModel> GetFilteredList(TransportSearchModel model)
{
if (string.IsNullOrEmpty(model.License))
{
return new();
}
using var context = new RouteGuideDatabase();
return context.Transport
.Include(x => x.Driver)
.Where(x => x.License.Contains(model.License))
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public TransportViewModel? GetElement(TransportSearchModel model)
{
if (!model.Id.HasValue && string.IsNullOrEmpty(model.License))
{
return null;
}
using var context = new RouteGuideDatabase();
return context.Transport
.Include(x => x.Driver)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.License) && x.License.Contains(model.License)) || (model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
/// <summary>
/// Добавление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public TransportViewModel? Insert(TransportBindingModel model)
{
using var context = new RouteGuideDatabase();
var newTransport = Transport.Create(context, model);
if (newTransport == null)
{
return null;
}
context.Transport.Add(newTransport);
context.SaveChanges();
return newTransport.GetViewModel;
}
/// <summary>
/// Редактирование элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public TransportViewModel? Update(TransportBindingModel model)
{
using var context = new RouteGuideDatabase();
var transport = context.Transport.FirstOrDefault(x => x.Id == model.Id);
if (transport == null)
{
return null;
}
transport.Update(model);
context.SaveChanges();
return transport.GetViewModel;
}
/// <summary>
/// Удаление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public TransportViewModel? Delete(TransportBindingModel model)
{
using var context = new RouteGuideDatabase();
var transport = context.Transport.FirstOrDefault(x => x.Id == model.Id);
if (transport == null)
{
return null;
}
context.Transport.Remove(transport);
context.SaveChanges();
return transport.GetViewModel;
}
}
}

View File

@ -0,0 +1,109 @@
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.ViewModels;
using RouteGuideDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RouteGuideDatabaseImplement.Models
{
/// <summary>
/// Сущность "Водитель"
/// </summary>
public class Driver : IDriverModel
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; private set; }
/// <summary>
/// ФИО водителя
/// </summary>
[Required]
public string FullName { get; private set; } = string.Empty;
/// <summary>
/// Номер телефона водителя
/// </summary>
[Required]
public string Phone { get; private set; } = string.Empty;
/// <summary>
/// Опыт работы водителя
/// </summary>
public int? Experience { get; private set; }
/// <summary>
/// Создание модели
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static Driver? Create(DriverBindingModel model)
{
if (model == null)
{
return null;
}
return new Driver()
{
Id = model.Id,
FullName = model.FullName,
Phone = model.Phone,
Experience = model.Experience
};
}
/// <summary>
/// Создание модели
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static Driver? Create(DriverViewModel model)
{
if (model == null)
{
return null;
}
return new Driver()
{
Id = model.Id,
FullName = model.FullName,
Phone = model.Phone,
Experience = model.Experience
};
}
/// <summary>
/// Изменение модели
/// </summary>
/// <param name="model"></param>
public void Update(DriverBindingModel model)
{
if (model == null)
{
return;
}
FullName = model.FullName;
Phone = model.Phone;
Experience = model.Experience;
}
/// <summary>
/// Получение модели
/// </summary>
public DriverViewModel GetViewModel => new()
{
Id = Id,
FullName = FullName,
Phone = Phone,
Experience = Experience
};
}
}

View File

@ -0,0 +1,154 @@
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
{
/// <summary>
/// Сущность "Маршрут"
/// </summary>
public class Route : IRouteModel
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; private set; }
/// <summary>
/// Название маршрута
/// </summary>
[Required]
public string Name { get; private set; } = string.Empty;
/// <summary>
/// Идентификатор транспорта
/// </summary>
[ForeignKey("TransportId")]
public int TransportId { get; private set; }
/// <summary>
/// Сущность "Транспорт"
/// </summary>
public virtual Transport Transport { get; private set; } = new();
/// <summary>
/// Коллекция остановок маршрута
/// </summary>
private Dictionary<int, (IStopModel, int)>? _routeStops = null;
/// <summary>
/// Коллекция остановок маршрута
/// </summary>
[NotMapped]
public Dictionary<int, (IStopModel, int)> RouteStops
{
get
{
if (_routeStops == null)
{
_routeStops = Stops
.ToDictionary(recRS => recRS.StopId, recRS => (recRS.Stop as IStopModel, recRS.Number));
}
return _routeStops;
}
}
/// <summary>
/// Связь с классом связи маршрутов и остановок
/// </summary>
[ForeignKey("RouteId")]
public virtual List<RouteStop> Stops { get; set; } = new();
/// <summary>
/// Созданме модели
/// </summary>
/// <param name="context"></param>
/// <param name="model"></param>
/// <returns></returns>
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()
};
}
/// <summary>
/// Изменение модели
/// </summary>
/// <param name="model"></param>
public void Update(RouteBindingModel model)
{
if (model == null)
{
return;
}
Name = model.Name;
}
/// <summary>
/// Получение модели
/// </summary>
public RouteViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
TransportId = TransportId,
RouteStops = RouteStops
};
/// <summary>
/// Обновление списка связей
/// </summary>
/// <param name="context"></param>
/// <param name="model"></param>
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;
}
}
}

View File

@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RouteGuideDatabaseImplement.Models
{
/// <summary>
/// Класс связи сущностей "Маршрут" и "Остановка"
/// </summary>
public class RouteStop
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; set; }
/// <summary>
/// Идентификатор маршрута
/// </summary>
[Required]
public int RouteId { get; set; }
/// <summary>
/// Сущность "Маршрут"
/// </summary>
public virtual Route Route { get; set; } = new();
/// <summary>
/// Идентификатор остановки
/// </summary>
[Required]
public int StopId { get; set; }
/// <summary>
/// Сущность "Остановка"
/// </summary>
public virtual Stop Stop { get; set; } = new();
/// <summary>
/// Номер остановки в маршруте
/// </summary>
[Required]
public int Number { get; set; }
}
}

View File

@ -0,0 +1,115 @@
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.ViewModels;
using RouteGuideDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RouteGuideDatabaseImplement.Models
{
/// <summary>
/// Сущность "Расписание"
/// </summary>
public class Schedule : IScheduleModel
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; private set; }
/// <summary>
/// Дата записи расписания
/// </summary>
[Required]
public DateTime Date { get; private set; } = DateTime.Now;
/// <summary>
/// Время отправления
/// </summary>
[Required]
public DateTime DepartureTime { get; private set; } = DateTime.MinValue;
/// <summary>
/// Время прибытия
/// </summary>
[Required]
public DateTime ArrivalTime { get; private set; } = DateTime.MinValue;
/// <summary>
/// Периодичность движения транспорта
/// </summary>
[Required]
public DateTime Frequency { get; private set; } = DateTime.MinValue;
/// <summary>
/// Идентификатор маршрута
/// </summary>
[ForeignKey("RouteId")]
public int RouteId { get; private set; }
/// <summary>
/// Сущность "Маршрут"
/// </summary>
public virtual Route Route { get; private set; } = new();
/// <summary>
/// Создание модели
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static Schedule? Create(RouteGuideDatabase context, ScheduleBindingModel model)
{
if (model == null)
{
return null;
}
return new Schedule()
{
Id = model.Id,
Date = model.Date,
DepartureTime = model.DepartureTime,
ArrivalTime = model.ArrivalTime,
Frequency = model.Frequency,
RouteId = model.RouteId,
Route = context.Routes
.FirstOrDefault(x => x.Id == model.RouteId)
};
}
/// <summary>
/// Изменение модели
/// </summary>
/// <param name="model"></param>
public void Update(ScheduleBindingModel model)
{
if (model == null)
{
return;
}
Date = model.Date;
DepartureTime = model.DepartureTime;
ArrivalTime = model.ArrivalTime;
Frequency = model.Frequency;
}
/// <summary>
/// Получение модели
/// </summary>
public ScheduleViewModel GetViewModel => new()
{
Id = Id,
Date = Date,
DepartureTime = DepartureTime,
ArrivalTime = ArrivalTime,
Frequency = Frequency,
RouteId = RouteId
};
}
}

View File

@ -0,0 +1,111 @@
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.ViewModels;
using RouteGuideDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace RouteGuideDatabaseImplement.Models
{
/// <summary>
/// Сущность "Остановка"
/// </summary>
public class Stop : IStopModel
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; private set; }
/// <summary>
/// Название остановки
/// </summary>
[Required]
public string Name { get; private set; } = string.Empty;
/// <summary>
/// Название улицы
/// </summary>
[Required]
public string Street { get; private set; } = string.Empty;
/// <summary>
/// Номер дома
/// </summary>
[Required]
public int Number { get; private set; }
/// <summary>
/// Создание модели
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static Stop? Create(StopBindingModel model)
{
if (model == null)
{
return null;
}
return new Stop()
{
Id = model.Id,
Name = model.Name,
Street = model.Street,
Number = model.Number
};
}
/// <summary>
/// Создание модели
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static Stop? Create(StopViewModel model)
{
if (model == null)
{
return null;
}
return new Stop()
{
Id = model.Id,
Name = model.Name,
Street = model.Street,
Number = model.Number
};
}
/// <summary>
/// Изменение модели
/// </summary>
/// <param name="model"></param>
public void Update(StopBindingModel model)
{
if (model == null)
{
return;
}
Name = model.Name;
Street = model.Street;
Number = model.Number;
}
/// <summary>
/// Получение модели
/// </summary>
public StopViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Street = Street,
Number = Number
};
}
}

View File

@ -0,0 +1,105 @@
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.ViewModels;
using RouteGuideDataModels.Enums;
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
{
/// <summary>
/// Сущность "Транспорт"
/// </summary>
public class Transport : ITransportModel
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; private set; }
/// <summary>
/// Номерной знак
/// </summary>
[Required]
public string License { get; private set; } = string.Empty;
/// <summary>
/// Тип транспортного средства
/// </summary>
[Required]
public TransportType Type { get; private set; } = TransportType.Автобус;
/// <summary>
/// Вместимость (количество пассажиров)
/// </summary>
[Required]
public int Capacity { get; private set; }
/// <summary>
/// Идентификатор водителя
/// </summary>
[ForeignKey("DriverId")]
public int DriverId { get; private set; }
/// <summary>
/// Сущность "Водитель"
/// </summary>
public virtual Driver Driver { get; private set; } = new();
/// <summary>
/// Создание модели
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static Transport? Create(RouteGuideDatabase context, TransportBindingModel model)
{
if (model == null)
{
return null;
}
return new Transport()
{
Id = model.Id,
License = model.License,
Type = model.Type,
Capacity = model.Capacity,
DriverId = model.DriverId,
Driver = context.Drivers
.FirstOrDefault(x => x.Id == model.DriverId)
};
}
/// <summary>
/// Изменение модели
/// </summary>
/// <param name="model"></param>
public void Update(TransportBindingModel model)
{
if (model == null)
{
return;
}
License = model.License;
Capacity = model.Capacity;
}
/// <summary>
/// Получение модели
/// </summary>
public TransportViewModel GetViewModel => new()
{
Id = Id,
License = License,
Type = Type,
DriverId = DriverId
};
}
}

View File

@ -0,0 +1,64 @@
using Microsoft.EntityFrameworkCore;
using RouteGuideDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RouteGuideDatabaseImplement
{
/// <summary>
/// Класс для взаимодействия с базой данных
/// </summary>
public class RouteGuideDatabase : DbContext
{
/// <summary>
/// Параметры подключения к базе данных
/// </summary>
private string _dbConnectionString = "Host=192.168.0.108;Port=5432;Database=RouteGuide;Username=postgres;Password=2004";
/// <summary>
/// Подключение к базе данных
/// </summary>
/// <param name="optionsBuilder"></param>
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseNpgsql(_dbConnectionString);
}
base.OnConfiguring(optionsBuilder);
}
/// <summary>
/// Таблица "Водители"
/// </summary>
public virtual DbSet<Driver> Drivers { get; set; }
/// <summary>
/// Таблица "Транспорт"
/// </summary>
public virtual DbSet<Transport> Transport { get; set; }
/// <summary>
/// Таблица "Маршруты"
/// </summary>
public virtual DbSet<Route> Routes { get; set; }
/// <summary>
/// Таблица "Остановки"
/// </summary>
public virtual DbSet<Stop> Stops { get; set; }
/// <summary>
/// Связь для сущностей "Маршруты" и "Остановки"
/// </summary>
public virtual DbSet<RouteStop> RouteStops { get; set; }
/// <summary>
/// Таблица "Расписания"
/// </summary>
public virtual DbSet<Schedule> Schedules { get; set; }
}
}

View File

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\RouteGuideContracts\RouteGuideContracts.csproj" />
<ProjectReference Include="..\RouteGuideDataModels\RouteGuideDataModels.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.13" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.13">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.4" />
</ItemGroup>
</Project>