Compare commits

..

2 Commits

Author SHA1 Message Date
ab513e4064 MongoDBImplement / Add Data transfer 2024-04-25 18:39:04 +04:00
63995f51c2 MongoDBImplement 2024-04-23 19:38:25 +04:00
67 changed files with 2663 additions and 592 deletions

View File

@ -11,7 +11,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RouteGuideContracts", "Rout
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RouteGuideDatabaseImplement", "RouteGuideDatabaseImplement\RouteGuideDatabaseImplement.csproj", "{5C2BBCAA-01A8-4B4C-B296-E7CF8DFBA884}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RouteGuideDatabaseImplement", "RouteGuideDatabaseImplement\RouteGuideDatabaseImplement.csproj", "{5C2BBCAA-01A8-4B4C-B296-E7CF8DFBA884}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RouteGuideBusinessLogics", "RouteGuideBusinessLogics\RouteGuideBusinessLogics.csproj", "{7B6C15DA-C491-4EE1-BEC8-C7FE580C2BA2}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RouteGuideBusinessLogics", "RouteGuideBusinessLogics\RouteGuideBusinessLogics.csproj", "{7B6C15DA-C491-4EE1-BEC8-C7FE580C2BA2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RouteGuideMongoDBImplement", "RouteGuideMongoDBImplement\RouteGuideMongoDBImplement.csproj", "{4FC074A5-4AB9-40C5-8833-B0A7D138F675}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -39,6 +41,10 @@ Global
{7B6C15DA-C491-4EE1-BEC8-C7FE580C2BA2}.Debug|Any CPU.Build.0 = Debug|Any CPU {7B6C15DA-C491-4EE1-BEC8-C7FE580C2BA2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7B6C15DA-C491-4EE1-BEC8-C7FE580C2BA2}.Release|Any CPU.ActiveCfg = Release|Any CPU {7B6C15DA-C491-4EE1-BEC8-C7FE580C2BA2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7B6C15DA-C491-4EE1-BEC8-C7FE580C2BA2}.Release|Any CPU.Build.0 = Release|Any CPU {7B6C15DA-C491-4EE1-BEC8-C7FE580C2BA2}.Release|Any CPU.Build.0 = Release|Any CPU
{4FC074A5-4AB9-40C5-8833-B0A7D138F675}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4FC074A5-4AB9-40C5-8833-B0A7D138F675}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4FC074A5-4AB9-40C5-8833-B0A7D138F675}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4FC074A5-4AB9-40C5-8833-B0A7D138F675}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@ -216,7 +216,7 @@ namespace RouteGuideBusinessLogics.BusinessLogics
{ {
Phone = model.Phone Phone = model.Phone
}); });
if (element != null && element.Id != model.Id) if (element != null && !element.Id.Equals(model.Id))
{ {
throw new InvalidOperationException("Водитель с таким номером телефона уже существует"); throw new InvalidOperationException("Водитель с таким номером телефона уже существует");
} }

View File

@ -204,7 +204,7 @@ namespace RouteGuideBusinessLogics.BusinessLogics
{ {
throw new ArgumentNullException("Не указано название маршрута", nameof(model.Name)); throw new ArgumentNullException("Не указано название маршрута", nameof(model.Name));
} }
if (model.TransportId < 0) if (model.TransportId == null || (model.TransportId is int && (int)model.TransportId < 0))
{ {
throw new ArgumentNullException("Некорректный идентификатор транспортного средства", nameof(model.TransportId)); throw new ArgumentNullException("Некорректный идентификатор транспортного средства", nameof(model.TransportId));
} }
@ -215,7 +215,7 @@ namespace RouteGuideBusinessLogics.BusinessLogics
{ {
Name = model.Name Name = model.Name
}); });
if (element != null && element.Id != model.Id) if (element != null && !element.Id.Equals(model.Id))
{ {
throw new InvalidOperationException("Маршрут с таким названием уже существует"); throw new InvalidOperationException("Маршрут с таким названием уже существует");
} }

View File

@ -200,7 +200,7 @@ namespace RouteGuideBusinessLogics.BusinessLogics
{ {
return; return;
} }
if (model.RouteId < 0) if (model.RouteId == null || (model.RouteId is int && (int)model.RouteId < 0))
{ {
throw new ArgumentNullException("Некорректный идентификатор маршрута", nameof(model.RouteId)); throw new ArgumentNullException("Некорректный идентификатор маршрута", nameof(model.RouteId));
} }

View File

@ -219,7 +219,7 @@ namespace RouteGuideBusinessLogics.BusinessLogics
{ {
Name = model.Name Name = model.Name
}); });
if (element != null && element.Id != model.Id) if (element != null && !element.Id.Equals(model.Id))
{ {
throw new InvalidOperationException("Остановка с таким названием уже существует"); throw new InvalidOperationException("Остановка с таким названием уже существует");
} }

View File

@ -208,7 +208,7 @@ namespace RouteGuideBusinessLogics.BusinessLogics
{ {
throw new ArgumentNullException("Вместимость транспортного средства должна быть положительным числом", nameof(model.Capacity)); throw new ArgumentNullException("Вместимость транспортного средства должна быть положительным числом", nameof(model.Capacity));
} }
if (model.DriverId < 0) if (model.DriverId == null || (model.DriverId is int && (int)model.DriverId < 0))
{ {
throw new ArgumentNullException("Некорректный идентификатор водителя", nameof(model.DriverId)); throw new ArgumentNullException("Некорректный идентификатор водителя", nameof(model.DriverId));
} }
@ -219,7 +219,7 @@ namespace RouteGuideBusinessLogics.BusinessLogics
{ {
License = model.License License = model.License
}); });
if (element != null && element.Id != model.Id) if (element != null && !element.Id.Equals(model.Id))
{ {
throw new InvalidOperationException("Транспортное средство с таким номерным знаком уже есть"); throw new InvalidOperationException("Транспортное средство с таким номерным знаком уже есть");
} }

View File

@ -11,12 +11,12 @@ namespace RouteGuideContracts.BindingModels
/// Модель для передачи данных пользователя /// Модель для передачи данных пользователя
/// в методы для сохранения данных для водителей /// в методы для сохранения данных для водителей
/// </summary> /// </summary>
public class DriverBindingModel : IDriverModel public class DriverBindingModel : IDriverModel<object>
{ {
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
public int Id { get; set; } public object Id { get; set; }
/// <summary> /// <summary>
/// ФИО водителя /// ФИО водителя

View File

@ -11,12 +11,12 @@ namespace RouteGuideContracts.BindingModels
/// Модель для передачи данных пользователя /// Модель для передачи данных пользователя
/// в методы для сохранения данных для маршрутов /// в методы для сохранения данных для маршрутов
/// </summary> /// </summary>
public class RouteBindingModel : IRouteModel public class RouteBindingModel : IRouteModel<object>
{ {
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
public int Id { get; set; } public object Id { get; set; }
/// <summary> /// <summary>
/// Название маршрута /// Название маршрута
@ -26,12 +26,12 @@ namespace RouteGuideContracts.BindingModels
/// <summary> /// <summary>
/// Идентификатор транспорта /// Идентификатор транспорта
/// </summary> /// </summary>
public int TransportId { get; set; } public object TransportId { get; set; }
/// <summary> /// <summary>
/// Коллекция остановок маршрута /// Коллекция остановок маршрута
/// </summary> /// </summary>
public Dictionary<int, (IStopModel, int)> RouteStops public Dictionary<object, (IStopModel<object>, int)> RouteStops
{ {
get; get;
set; set;

View File

@ -11,12 +11,12 @@ namespace RouteGuideContracts.BindingModels
/// Модель для передачи данных пользователя /// Модель для передачи данных пользователя
/// в методы для сохранения данных для расписания /// в методы для сохранения данных для расписания
/// </summary> /// </summary>
public class ScheduleBindingModel : IScheduleModel public class ScheduleBindingModel : IScheduleModel<object>
{ {
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
public int Id { get; set; } public object Id { get; set; }
/// <summary> /// <summary>
/// Дата записи расписания /// Дата записи расписания
@ -41,6 +41,6 @@ namespace RouteGuideContracts.BindingModels
/// <summary> /// <summary>
/// Идентификатор маршрута /// Идентификатор маршрута
/// </summary> /// </summary>
public int RouteId { get; set; } public object RouteId { get; set; }
} }
} }

View File

@ -11,12 +11,12 @@ namespace RouteGuideContracts.BindingModels
/// Модель для передачи данных пользователя /// Модель для передачи данных пользователя
/// в методы для сохранения данных для остановок /// в методы для сохранения данных для остановок
/// </summary> /// </summary>
public class StopBindingModel : IStopModel public class StopBindingModel : IStopModel<object>
{ {
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
public int Id { get; set; } public object Id { get; set; }
/// <summary> /// <summary>
/// Название остановки /// Название остановки

View File

@ -12,12 +12,12 @@ namespace RouteGuideContracts.BindingModels
/// Модель для передачи данных пользователя /// Модель для передачи данных пользователя
/// в методы для сохранения данных для транспорта /// в методы для сохранения данных для транспорта
/// </summary> /// </summary>
public class TransportBindingModel : ITransportModel public class TransportBindingModel : ITransportModel<object>
{ {
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
public int Id { get; set; } public object Id { get; set; }
/// <summary> /// <summary>
/// Номерной знак /// Номерной знак
@ -37,6 +37,6 @@ namespace RouteGuideContracts.BindingModels
/// <summary> /// <summary>
/// Идентификатор водителя /// Идентификатор водителя
/// </summary> /// </summary>
public int DriverId { get; set; } public object DriverId { get; set; }
} }
} }

View File

@ -15,7 +15,7 @@ namespace RouteGuideContracts.SearchModels
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
public int? Id { get; set; } public object? Id { get; set; }
/// <summary> /// <summary>
/// Номер телефона водителя /// Номер телефона водителя

View File

@ -15,7 +15,7 @@ namespace RouteGuideContracts.SearchModels
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
public int? Id { get; set; } public object? Id { get; set; }
/// <summary> /// <summary>
/// Название маршрута /// Название маршрута

View File

@ -15,6 +15,6 @@ namespace RouteGuideContracts.SearchModels
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
public int? Id { get; set; } public object? Id { get; set; }
} }
} }

View File

@ -15,7 +15,7 @@ namespace RouteGuideContracts.SearchModels
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
public int? Id { get; set; } public object? Id { get; set; }
/// <summary> /// <summary>
/// Название остановки /// Название остановки

View File

@ -15,7 +15,7 @@ namespace RouteGuideContracts.SearchModels
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
public int? Id { get; set; } public object? Id { get; set; }
/// <summary> /// <summary>
/// Номерной знак /// Номерной знак

View File

@ -12,12 +12,12 @@ namespace RouteGuideContracts.ViewModels
/// Модель для передачи данных пользователю /// Модель для передачи данных пользователю
/// для отображения для водителей /// для отображения для водителей
/// </summary> /// </summary>
public class DriverViewModel : IDriverModel public class DriverViewModel : IDriverModel<object>
{ {
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
public int Id { get; set; } public object Id { get; set; }
/// <summary> /// <summary>
/// ФИО водителя /// ФИО водителя

View File

@ -12,12 +12,12 @@ namespace RouteGuideContracts.ViewModels
/// Модель для передачи данных пользователю /// Модель для передачи данных пользователю
/// для отображения для маршрутов /// для отображения для маршрутов
/// </summary> /// </summary>
public class RouteViewModel : IRouteModel public class RouteViewModel : IRouteModel<object>
{ {
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
public int Id { get; set; } public object Id { get; set; }
/// <summary> /// <summary>
/// Название маршрута /// Название маршрута
@ -28,7 +28,7 @@ namespace RouteGuideContracts.ViewModels
/// <summary> /// <summary>
/// Идентификатор транспорта /// Идентификатор транспорта
/// </summary> /// </summary>
public int TransportId { get; set; } public object TransportId { get; set; }
/// <summary> /// <summary>
/// Номерной знак транспорта /// Номерной знак транспорта
@ -39,7 +39,7 @@ namespace RouteGuideContracts.ViewModels
/// <summary> /// <summary>
/// Коллекция остановок маршрута /// Коллекция остановок маршрута
/// </summary> /// </summary>
public Dictionary<int, (IStopModel, int)> RouteStops public Dictionary<object, (IStopModel<object>, int)> RouteStops
{ {
get; get;
set; set;

View File

@ -12,12 +12,12 @@ namespace RouteGuideContracts.ViewModels
/// Модель для передачи данных пользователю /// Модель для передачи данных пользователю
/// для отображения для расписания /// для отображения для расписания
/// </summary> /// </summary>
public class ScheduleViewModel : IScheduleModel public class ScheduleViewModel : IScheduleModel<object>
{ {
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
public int Id { get; set; } public object Id { get; set; }
/// <summary> /// <summary>
/// Дата записи расписания /// Дата записи расписания
@ -46,7 +46,7 @@ namespace RouteGuideContracts.ViewModels
/// <summary> /// <summary>
/// Идентификатор маршрута /// Идентификатор маршрута
/// </summary> /// </summary>
public int RouteId { get; set; } public object RouteId { get; set; }
/// <summary> /// <summary>
/// Название маршрута /// Название маршрута

View File

@ -12,12 +12,12 @@ namespace RouteGuideContracts.ViewModels
/// Модель для передачи данных пользователю /// Модель для передачи данных пользователю
/// для отображения для остановок /// для отображения для остановок
/// </summary> /// </summary>
public class StopViewModel : IStopModel public class StopViewModel : IStopModel<object>
{ {
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
public int Id { get; set; } public object Id { get; set; }
/// <summary> /// <summary>
/// Название остановки /// Название остановки

View File

@ -13,12 +13,12 @@ namespace RouteGuideContracts.ViewModels
/// Модель для передачи данных пользователю /// Модель для передачи данных пользователю
/// для отображения для транспорта /// для отображения для транспорта
/// </summary> /// </summary>
public class TransportViewModel : ITransportModel public class TransportViewModel : ITransportModel<object>
{ {
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
public int Id { get; set; } public object Id { get; set; }
/// <summary> /// <summary>
/// Номерной знак /// Номерной знак
@ -41,7 +41,7 @@ namespace RouteGuideContracts.ViewModels
/// <summary> /// <summary>
/// Идентификатор водителя /// Идентификатор водителя
/// </summary> /// </summary>
public int DriverId { get; set; } public object DriverId { get; set; }
/// <summary> /// <summary>
/// ФИО водителя /// ФИО водителя

View File

@ -9,11 +9,12 @@ namespace RouteGuideDataModels
/// <summary> /// <summary>
/// Интерфейс для идентификатора /// Интерфейс для идентификатора
/// </summary> /// </summary>
public interface IId public interface IId<T>
{
{
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
int Id { get; } T Id { get; }
} }
} }

View File

@ -9,7 +9,7 @@ namespace RouteGuideDataModels.Models
/// <summary> /// <summary>
/// Интерфейс для модели водителя /// Интерфейс для модели водителя
/// </summary> /// </summary>
public interface IDriverModel : IId public interface IDriverModel<T> : IId<T>
{ {
/// <summary> /// <summary>
/// ФИО водителя /// ФИО водителя

View File

@ -9,7 +9,7 @@ namespace RouteGuideDataModels.Models
/// <summary> /// <summary>
/// Интерфейс для модели маршрута /// Интерфейс для модели маршрута
/// </summary> /// </summary>
public interface IRouteModel : IId public interface IRouteModel<T> : IId<T>
{ {
/// <summary> /// <summary>
/// Название маршрута /// Название маршрута
@ -19,11 +19,11 @@ namespace RouteGuideDataModels.Models
/// <summary> /// <summary>
/// Идентификатор транспорта /// Идентификатор транспорта
/// </summary> /// </summary>
int TransportId { get; } T TransportId { get; }
/// <summary> /// <summary>
/// Коллекция остановок маршрута /// Коллекция остановок маршрута
/// </summary> /// </summary>
Dictionary<int, (IStopModel, int)> RouteStops { get; } Dictionary<T, (IStopModel<T>, int)> RouteStops { get; }
} }
} }

View File

@ -9,7 +9,7 @@ namespace RouteGuideDataModels.Models
/// <summary> /// <summary>
/// Интерфейс для модели расписания /// Интерфейс для модели расписания
/// </summary> /// </summary>
public interface IScheduleModel : IId public interface IScheduleModel<T> : IId<T>
{ {
/// <summary> /// <summary>
/// Дата записи расписания /// Дата записи расписания
@ -34,6 +34,6 @@ namespace RouteGuideDataModels.Models
/// <summary> /// <summary>
/// Идентификатор маршрута /// Идентификатор маршрута
/// </summary> /// </summary>
int RouteId { get; } T RouteId { get; }
} }
} }

View File

@ -9,7 +9,7 @@ namespace RouteGuideDataModels.Models
/// <summary> /// <summary>
/// Интерфейс для модели остановки /// Интерфейс для модели остановки
/// </summary> /// </summary>
public interface IStopModel : IId public interface IStopModel<T> : IId<T>
{ {
/// <summary> /// <summary>
/// Название остановки /// Название остановки

View File

@ -10,7 +10,7 @@ namespace RouteGuideDataModels.Models
/// <summary> /// <summary>
/// Интерфейс для модели транспорта /// Интерфейс для модели транспорта
/// </summary> /// </summary>
public interface ITransportModel : IId public interface ITransportModel<T> : IId<T>
{ {
/// <summary> /// <summary>
/// Номерной знак /// Номерной знак
@ -30,6 +30,6 @@ namespace RouteGuideDataModels.Models
/// <summary> /// <summary>
/// Идентификатор водителя /// Идентификатор водителя
/// </summary> /// </summary>
int DriverId { get; } T DriverId { get; }
} }
} }

View File

@ -74,14 +74,14 @@ namespace RouteGuideDatabaseImplement.Implements
/// <returns></returns> /// <returns></returns>
public DriverViewModel? GetElement(DriverSearchModel model) public DriverViewModel? GetElement(DriverSearchModel model)
{ {
if (!model.Id.HasValue && string.IsNullOrEmpty(model.Phone)) if (model.Id == null && string.IsNullOrEmpty(model.Phone))
{ {
return null; return null;
} }
using var context = new RouteGuideDatabase(); using var context = new RouteGuideDatabase();
return context.Drivers return context.Drivers
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Phone) && x.Phone.Contains(model.Phone)) || (model.Id.HasValue && x.Id == model.Id)) .FirstOrDefault(x => (!string.IsNullOrEmpty(model.Phone) && x.Phone.Contains(model.Phone)) || (model.Id != null && x.Id.Equals(model.Id)))
?.GetViewModel; ?.GetViewModel;
} }
@ -112,7 +112,7 @@ namespace RouteGuideDatabaseImplement.Implements
public DriverViewModel? Update(DriverBindingModel model) public DriverViewModel? Update(DriverBindingModel model)
{ {
using var context = new RouteGuideDatabase(); using var context = new RouteGuideDatabase();
var driver = context.Drivers.FirstOrDefault(x => x.Id == model.Id); var driver = context.Drivers.FirstOrDefault(x => x.Id.Equals(model.Id));
if (driver == null) if (driver == null)
{ {
return null; return null;
@ -131,7 +131,7 @@ namespace RouteGuideDatabaseImplement.Implements
public DriverViewModel? Delete(DriverBindingModel model) public DriverViewModel? Delete(DriverBindingModel model)
{ {
using var context = new RouteGuideDatabase(); using var context = new RouteGuideDatabase();
var driver = context.Drivers.FirstOrDefault(x => x.Id == model.Id); var driver = context.Drivers.FirstOrDefault(x => x.Id.Equals(model.Id));
if (driver == null) if (driver == null)
{ {
return null; return null;

View File

@ -86,7 +86,7 @@ namespace RouteGuideDatabaseImplement.Implements
/// <returns></returns> /// <returns></returns>
public RouteViewModel? GetElement(RouteSearchModel model) public RouteViewModel? GetElement(RouteSearchModel model)
{ {
if (!model.Id.HasValue && string.IsNullOrEmpty(model.Name)) if (model.Id == null && string.IsNullOrEmpty(model.Name))
{ {
return null; return null;
} }
@ -96,7 +96,7 @@ namespace RouteGuideDatabaseImplement.Implements
.Include(x => x.Transport) .Include(x => x.Transport)
.Include(x => x.Stops) .Include(x => x.Stops)
.ThenInclude(x => x.Stop) .ThenInclude(x => x.Stop)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name.Contains(model.Name)) || (model.Id.HasValue && x.Id == model.Id)) .FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name.Contains(model.Name)) || (model.Id != null && x.Id.Equals(model.Id)))
?.GetViewModel; ?.GetViewModel;
} }
@ -130,7 +130,7 @@ namespace RouteGuideDatabaseImplement.Implements
using var transaction = context.Database.BeginTransaction(); using var transaction = context.Database.BeginTransaction();
try try
{ {
var route = context.Routes.FirstOrDefault(x => x.Id == model.Id); var route = context.Routes.FirstOrDefault(x => x.Id.Equals(model.Id));
if (route == null) if (route == null)
{ {
return null; return null;
@ -159,7 +159,7 @@ namespace RouteGuideDatabaseImplement.Implements
using var context = new RouteGuideDatabase(); using var context = new RouteGuideDatabase();
var route = context.Routes var route = context.Routes
.Include(x => x.Stops) .Include(x => x.Stops)
.FirstOrDefault(rec => rec.Id == model.Id); .FirstOrDefault(rec => rec.Id.Equals(model.Id));
if (route == null) if (route == null)
{ {
return null; return null;

View File

@ -37,7 +37,7 @@ namespace RouteGuideDatabaseImplement.Implements
/// <returns></returns> /// <returns></returns>
public List<ScheduleViewModel> GetFilteredList(ScheduleSearchModel model) public List<ScheduleViewModel> GetFilteredList(ScheduleSearchModel model)
{ {
if (!model.Id.HasValue) if (model.Id == null)
{ {
return new(); return new();
} }
@ -45,7 +45,7 @@ namespace RouteGuideDatabaseImplement.Implements
using var context = new RouteGuideDatabase(); using var context = new RouteGuideDatabase();
return context.Schedules return context.Schedules
.Include(x => x.Route) .Include(x => x.Route)
.Where(x => x.Id == model.Id) .Where(x => x.Id.Equals(model.Id))
.Select(x => x.GetViewModel) .Select(x => x.GetViewModel)
.ToList(); .ToList();
} }
@ -77,7 +77,7 @@ namespace RouteGuideDatabaseImplement.Implements
/// <returns></returns> /// <returns></returns>
public ScheduleViewModel? GetElement(ScheduleSearchModel model) public ScheduleViewModel? GetElement(ScheduleSearchModel model)
{ {
if (!model.Id.HasValue) if (model.Id == null)
{ {
return null; return null;
} }
@ -85,7 +85,7 @@ namespace RouteGuideDatabaseImplement.Implements
using var context = new RouteGuideDatabase(); using var context = new RouteGuideDatabase();
return context.Schedules return context.Schedules
.Include(x => x.Route) .Include(x => x.Route)
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id)) .FirstOrDefault(x => (model.Id != null && x.Id.Equals(model.Id)))
?.GetViewModel; ?.GetViewModel;
} }
@ -116,7 +116,7 @@ namespace RouteGuideDatabaseImplement.Implements
public ScheduleViewModel? Update(ScheduleBindingModel model) public ScheduleViewModel? Update(ScheduleBindingModel model)
{ {
using var context = new RouteGuideDatabase(); using var context = new RouteGuideDatabase();
var schedule = context.Schedules.FirstOrDefault(x => x.Id == model.Id); var schedule = context.Schedules.FirstOrDefault(x => x.Id.Equals(model.Id));
if (schedule == null) if (schedule == null)
{ {
return null; return null;
@ -135,7 +135,7 @@ namespace RouteGuideDatabaseImplement.Implements
public ScheduleViewModel? Delete(ScheduleBindingModel model) public ScheduleViewModel? Delete(ScheduleBindingModel model)
{ {
using var context = new RouteGuideDatabase(); using var context = new RouteGuideDatabase();
var schedule = context.Schedules.FirstOrDefault(x => x.Id == model.Id); var schedule = context.Schedules.FirstOrDefault(x => x.Id.Equals(model.Id));
if (schedule == null) if (schedule == null)
{ {
return null; return null;

View File

@ -73,14 +73,14 @@ namespace RouteGuideDatabaseImplement.Implements
/// <returns></returns> /// <returns></returns>
public StopViewModel? GetElement(StopSearchModel model) public StopViewModel? GetElement(StopSearchModel model)
{ {
if (!model.Id.HasValue && string.IsNullOrEmpty(model.Name)) if (model.Id == null && string.IsNullOrEmpty(model.Name))
{ {
return null; return null;
} }
using var context = new RouteGuideDatabase(); using var context = new RouteGuideDatabase();
return context.Stops return context.Stops
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name.Contains(model.Name)) || (model.Id.HasValue && x.Id == model.Id)) .FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name.Contains(model.Name)) || (model.Id != null && x.Id.Equals(model.Id)))
?.GetViewModel; ?.GetViewModel;
} }
@ -111,7 +111,7 @@ namespace RouteGuideDatabaseImplement.Implements
public StopViewModel? Update(StopBindingModel model) public StopViewModel? Update(StopBindingModel model)
{ {
using var context = new RouteGuideDatabase(); using var context = new RouteGuideDatabase();
var stop = context.Stops.FirstOrDefault(x => x.Id == model.Id); var stop = context.Stops.FirstOrDefault(x => x.Id.Equals(model.Id));
if (stop == null) if (stop == null)
{ {
return null; return null;
@ -130,7 +130,7 @@ namespace RouteGuideDatabaseImplement.Implements
public StopViewModel? Delete(StopBindingModel model) public StopViewModel? Delete(StopBindingModel model)
{ {
using var context = new RouteGuideDatabase(); using var context = new RouteGuideDatabase();
var stop = context.Stops.FirstOrDefault(x => x.Id == model.Id); var stop = context.Stops.FirstOrDefault(x => x.Id.Equals(model.Id));
if (stop == null) if (stop == null)
{ {
return null; return null;

View File

@ -77,7 +77,7 @@ namespace RouteGuideDatabaseImplement.Implements
/// <returns></returns> /// <returns></returns>
public TransportViewModel? GetElement(TransportSearchModel model) public TransportViewModel? GetElement(TransportSearchModel model)
{ {
if (!model.Id.HasValue && string.IsNullOrEmpty(model.License)) if (model.Id == null && string.IsNullOrEmpty(model.License))
{ {
return null; return null;
} }
@ -85,7 +85,7 @@ namespace RouteGuideDatabaseImplement.Implements
using var context = new RouteGuideDatabase(); using var context = new RouteGuideDatabase();
return context.Transport return context.Transport
.Include(x => x.Driver) .Include(x => x.Driver)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.License) && x.License.Contains(model.License)) || (model.Id.HasValue && x.Id == model.Id)) .FirstOrDefault(x => (!string.IsNullOrEmpty(model.License) && x.License.Contains(model.License)) || (model.Id != null && x.Id.Equals(model.Id)))
?.GetViewModel; ?.GetViewModel;
} }
@ -116,7 +116,7 @@ namespace RouteGuideDatabaseImplement.Implements
public TransportViewModel? Update(TransportBindingModel model) public TransportViewModel? Update(TransportBindingModel model)
{ {
using var context = new RouteGuideDatabase(); using var context = new RouteGuideDatabase();
var transport = context.Transport.FirstOrDefault(x => x.Id == model.Id); var transport = context.Transport.FirstOrDefault(x => x.Id.Equals(model.Id));
if (transport == null) if (transport == null)
{ {
return null; return null;
@ -135,7 +135,7 @@ namespace RouteGuideDatabaseImplement.Implements
public TransportViewModel? Delete(TransportBindingModel model) public TransportViewModel? Delete(TransportBindingModel model)
{ {
using var context = new RouteGuideDatabase(); using var context = new RouteGuideDatabase();
var transport = context.Transport.FirstOrDefault(x => x.Id == model.Id); var transport = context.Transport.FirstOrDefault(x => x.Id.Equals(model.Id));
if (transport == null) if (transport == null)
{ {
return null; return null;

View File

@ -13,7 +13,7 @@ namespace RouteGuideDatabaseImplement.Models
/// <summary> /// <summary>
/// Сущность "Водитель" /// Сущность "Водитель"
/// </summary> /// </summary>
public class Driver : IDriverModel public class Driver : IDriverModel<int>
{ {
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
@ -51,7 +51,7 @@ namespace RouteGuideDatabaseImplement.Models
return new Driver() return new Driver()
{ {
Id = model.Id, Id = (int)model.Id,
FullName = model.FullName, FullName = model.FullName,
Phone = model.Phone, Phone = model.Phone,
Experience = model.Experience Experience = model.Experience
@ -72,7 +72,7 @@ namespace RouteGuideDatabaseImplement.Models
return new Driver() return new Driver()
{ {
Id = model.Id, Id = (int)model.Id,
FullName = model.FullName, FullName = model.FullName,
Phone = model.Phone, Phone = model.Phone,
Experience = model.Experience Experience = model.Experience

View File

@ -15,7 +15,7 @@ namespace RouteGuideDatabaseImplement.Models
/// <summary> /// <summary>
/// Сущность "Маршрут" /// Сущность "Маршрут"
/// </summary> /// </summary>
public class Route : IRouteModel public class Route : IRouteModel<int>
{ {
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
@ -42,20 +42,20 @@ namespace RouteGuideDatabaseImplement.Models
/// <summary> /// <summary>
/// Коллекция остановок маршрута /// Коллекция остановок маршрута
/// </summary> /// </summary>
private Dictionary<int, (IStopModel, int)>? _routeStops = null; private Dictionary<int, (IStopModel<int>, int)>? _routeStops = null;
/// <summary> /// <summary>
/// Коллекция остановок маршрута /// Коллекция остановок маршрута
/// </summary> /// </summary>
[NotMapped] [NotMapped]
public Dictionary<int, (IStopModel, int)> RouteStops public Dictionary<int, (IStopModel<int>, int)> RouteStops
{ {
get get
{ {
if (_routeStops == null) if (_routeStops == null)
{ {
_routeStops = Stops _routeStops = Stops
.ToDictionary(recRS => recRS.StopId, recRS => (recRS.Stop as IStopModel, recRS.Number)); .ToDictionary(recRS => recRS.StopId, recRS => (recRS.Stop as IStopModel<int>, recRS.Number));
} }
return _routeStops; return _routeStops;
} }
@ -77,14 +77,14 @@ namespace RouteGuideDatabaseImplement.Models
{ {
return new Route() return new Route()
{ {
Id = model.Id, Id = (int)model.Id,
Name = model.Name, Name = model.Name,
TransportId = model.TransportId, TransportId = (int)model.TransportId,
Transport = context.Transport Transport = context.Transport
.FirstOrDefault(x => x.Id == model.TransportId), .FirstOrDefault(x => x.Id.Equals(model.TransportId)),
Stops = model.RouteStops.Select(x => new RouteStop Stops = model.RouteStops.Select(x => new RouteStop
{ {
Stop = context.Stops.First(y => y.Id == x.Key), Stop = context.Stops.First(y => y.Id.Equals(x.Key)),
Number = x.Value.Item2 Number = x.Value.Item2
}).ToList() }).ToList()
}; };
@ -112,7 +112,14 @@ namespace RouteGuideDatabaseImplement.Models
Id = Id, Id = Id,
Name = Name, Name = Name,
TransportId = TransportId, TransportId = TransportId,
RouteStops = RouteStops, RouteStops = RouteStops
.ToDictionary(recRS => (object)recRS.Key, recRS => (new StopViewModel()
{
Id = (object)recRS.Value.Item1.Id,
Name = recRS.Value.Item1.Name,
Street = recRS.Value.Item1.Street,
Number = recRS.Value.Item1.Number
} as IStopModel<object>, recRS.Value.Item2)),
TransportLicense = Transport.License TransportLicense = Transport.License
}; };
@ -123,7 +130,7 @@ namespace RouteGuideDatabaseImplement.Models
/// <param name="model"></param> /// <param name="model"></param>
public void UpdateStops(RouteGuideDatabase context, RouteBindingModel model) public void UpdateStops(RouteGuideDatabase context, RouteBindingModel model)
{ {
var routeStops = context.RouteStops.Where(rec => rec.RouteId == model.Id).ToList(); var routeStops = context.RouteStops.Where(rec => rec.RouteId.Equals(model.Id)).ToList();
if (routeStops != null && routeStops.Count > 0) if (routeStops != null && routeStops.Count > 0)
{ {
// Удаление остановок, которых нет в маршруте // Удаление остановок, которых нет в маршруте
@ -144,7 +151,7 @@ namespace RouteGuideDatabaseImplement.Models
context.RouteStops.Add(new RouteStop context.RouteStops.Add(new RouteStop
{ {
Route = route, Route = route,
Stop = context.Stops.First(x => x.Id == rs.Key), Stop = context.Stops.First(x => x.Id.Equals(rs.Key)),
Number = rs.Value.Item2 Number = rs.Value.Item2
}); });
context.SaveChanges(); context.SaveChanges();

View File

@ -15,7 +15,7 @@ namespace RouteGuideDatabaseImplement.Models
/// <summary> /// <summary>
/// Сущность "Расписание" /// Сущность "Расписание"
/// </summary> /// </summary>
public class Schedule : IScheduleModel public class Schedule : IScheduleModel<int>
{ {
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
@ -71,14 +71,14 @@ namespace RouteGuideDatabaseImplement.Models
return new Schedule() return new Schedule()
{ {
Id = model.Id, Id = (int)model.Id,
Date = model.Date, Date = model.Date,
DepartureTime = model.DepartureTime, DepartureTime = model.DepartureTime,
ArrivalTime = model.ArrivalTime, ArrivalTime = model.ArrivalTime,
Frequency = model.Frequency, Frequency = model.Frequency,
RouteId = model.RouteId, RouteId = (int)model.RouteId,
Route = context.Routes Route = context.Routes
.FirstOrDefault(x => x.Id == model.RouteId) .FirstOrDefault(x => x.Id.Equals(model.RouteId))
}; };
} }

View File

@ -14,7 +14,7 @@ namespace RouteGuideDatabaseImplement.Models
/// <summary> /// <summary>
/// Сущность "Остановка" /// Сущность "Остановка"
/// </summary> /// </summary>
public class Stop : IStopModel public class Stop : IStopModel<int>
{ {
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
@ -53,7 +53,7 @@ namespace RouteGuideDatabaseImplement.Models
return new Stop() return new Stop()
{ {
Id = model.Id, Id = (int)model.Id,
Name = model.Name, Name = model.Name,
Street = model.Street, Street = model.Street,
Number = model.Number Number = model.Number
@ -74,7 +74,7 @@ namespace RouteGuideDatabaseImplement.Models
return new Stop() return new Stop()
{ {
Id = model.Id, Id = (int)model.Id,
Name = model.Name, Name = model.Name,
Street = model.Street, Street = model.Street,
Number = model.Number Number = model.Number

View File

@ -16,7 +16,7 @@ namespace RouteGuideDatabaseImplement.Models
/// <summary> /// <summary>
/// Сущность "Транспорт" /// Сущность "Транспорт"
/// </summary> /// </summary>
public class Transport : ITransportModel public class Transport : ITransportModel<int>
{ {
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
@ -66,13 +66,13 @@ namespace RouteGuideDatabaseImplement.Models
return new Transport() return new Transport()
{ {
Id = model.Id, Id = (int)model.Id,
License = model.License, License = model.License,
Type = model.Type, Type = model.Type,
Capacity = model.Capacity, Capacity = model.Capacity,
DriverId = model.DriverId, DriverId = (int)model.DriverId,
Driver = context.Drivers Driver = context.Drivers
.FirstOrDefault(x => x.Id == model.DriverId) .FirstOrDefault(x => x.Id.Equals(model.DriverId))
}; };
} }

View File

@ -0,0 +1,234 @@
using MongoDB.Bson;
using MongoDB.Driver;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RouteGuideMongoDBImplement
{
/// <summary>
/// Класс для переноса данных между БД
/// </summary>
public class DataTransfer
{
/// <summary>
/// Параметры подключения к базе данных PostgreSQL
/// </summary>
private readonly string _pgsqlDBConnectionString = "Host=192.168.0.108;Port=5432;Database=RouteGuide;Username=postgres;Password=2004";
/// <summary>
/// Параметры подключения к базе данных MongoDB
/// </summary>
private readonly string _mongoDBConnectionString = "mongodb://localhost:27017";
/// <summary>
/// Название базы данных
/// </summary>
private readonly string _databaseName = "RouteGuideDatabase";
/// <summary>
/// Клиент MongoDB
/// </summary>
public readonly MongoClient _client;
/// <summary>
/// База данных MongoDB
/// </summary>
private readonly IMongoDatabase _database;
/// <summary>
/// Коллекция "Водители"
/// </summary>
private IMongoCollection<BsonDocument> Drivers => _database.GetCollection<BsonDocument>("Drivers");
/// <summary>
/// Коллекция "Транспорт"
/// </summary>
private IMongoCollection<BsonDocument> Transport => _database.GetCollection<BsonDocument>("Transport");
/// <summary>
/// Коллекция "Маршруты"
/// </summary>
private IMongoCollection<BsonDocument> Routes => _database.GetCollection<BsonDocument>("Routes");
/// <summary>
/// Коллекция "Остановки"
/// </summary>
private IMongoCollection<BsonDocument> Stops => _database.GetCollection<BsonDocument>("Stops");
/// <summary>
/// Связь для сущностей "Маршруты" и "Остановки"
/// </summary>
private IMongoCollection<BsonDocument> RouteStops => _database.GetCollection<BsonDocument>("RouteStops");
/// <summary>
/// Коллекция "Расписания"
/// </summary>
private IMongoCollection<BsonDocument> Schedules => _database.GetCollection<BsonDocument>("Schedules");
/// <summary>
/// Конструктор
/// </summary>
public DataTransfer()
{
_client = new MongoClient(_mongoDBConnectionString);
_database = _client.GetDatabase(_databaseName);
}
/// <summary>
/// Начать перенос данных
/// </summary>
public void SyncData()
{
// Переносим данные
Transfer("Drivers");
Transfer("Transport");
Transfer("Routes");
Transfer("Stops");
Transfer("RouteStops");
Transfer("Schedules");
// Настраиваем корректные связи
var transportCollection = Transport.Find(Builders<BsonDocument>.Filter.Empty).ToList();
var routesCollection = Routes.Find(Builders<BsonDocument>.Filter.Empty).ToList();
var schedulesCollection = Schedules.Find(Builders<BsonDocument>.Filter.Empty).ToList();
// Связь между сущностями "Транспорт" и "Водитель"
transportCollection.ForEach(t =>
{
int tempDriverId = t.GetValue("DriverId").ToInt32();
var driverId = Drivers
.Find(Builders<BsonDocument>.Filter.Eq("Id", tempDriverId))
.FirstOrDefaultAsync()
.Result.GetValue("_id")
.ToString();
var driver = Drivers
.Find(Builders<BsonDocument>.Filter.Eq("Id", tempDriverId))
.Project(Builders<BsonDocument>.Projection.Exclude("Id"))
.FirstOrDefault();
var filter = Builders<BsonDocument>.Filter.Eq("_id", t.GetValue("_id"));
var updateDriverId = Builders<BsonDocument>.Update.Set("DriverId", driverId);
var updateDriver = Builders<BsonDocument>.Update.Set("Driver", driver);
Transport.UpdateOneAsync(filter, updateDriverId);
Transport.UpdateOneAsync(filter, updateDriver);
});
// Связь между сущностями "Маршрут" и "Транспорт"
routesCollection.ForEach(r =>
{
int tempTransportId = r.GetValue("TransportId").ToInt32();
var transportId = Transport
.Find(Builders<BsonDocument>.Filter.Eq("Id", tempTransportId))
.FirstOrDefaultAsync()
.Result.GetValue("_id")
.ToString();
var transport = Transport
.Find(Builders<BsonDocument>.Filter.Eq("Id", tempTransportId))
.Project(Builders<BsonDocument>.Projection.Exclude("Id"))
.FirstOrDefault();
var filter = Builders<BsonDocument>.Filter.Eq("_id", r.GetValue("_id"));
var updateTransportId = Builders<BsonDocument>.Update.Set("TransportId", transportId);
var updateTransport = Builders<BsonDocument>.Update.Set("Transport", transport);
Routes.UpdateOneAsync(filter, updateTransportId);
Routes.UpdateOneAsync(filter, updateTransport);
});
// Связь между сущностями "Маршруты" и "Остановки"
routesCollection.ForEach(r =>
{
var tempRouteId = r.GetValue("Id").ToInt32();
var routeStops = RouteStops
.Find(Builders<BsonDocument>.Filter.Eq("RouteId", tempRouteId))
.ToList();
var updateStops = new Dictionary<string, (BsonDocument, int)>();
routeStops.ForEach(rs =>
{
var tempStopId = rs.GetValue("StopId").ToInt32();
var stop = Stops
.Find(Builders<BsonDocument>.Filter.Eq("Id", tempStopId))
.Project(Builders<BsonDocument>.Projection.Exclude("Id"))
.FirstOrDefault();
if (stop != null)
{
var stopId = stop.GetValue("_id").ToString();
var stopNumber = rs.GetValue("Number").ToInt32();
updateStops.Add(stopId!, (stop, stopNumber));
}
});
var filter = Builders<BsonDocument>.Filter.Eq("_id", r.GetValue("_id"));
var update = Builders<BsonDocument>.Update.Set("Stops", updateStops);
Routes.UpdateOneAsync(filter, update);
});
// Связь между сущностями "Расписание" и "Маршрут"
schedulesCollection.ForEach(s =>
{
int tempRouteId = s.GetValue("RouteId").ToInt32();
var routeId = Routes
.Find(Builders<BsonDocument>.Filter.Eq("Id", tempRouteId))
.FirstOrDefaultAsync()
.Result.GetValue("_id")
.ToString();
var route = Routes
.Find(Builders<BsonDocument>.Filter.Eq("Id", tempRouteId))
.Project(Builders<BsonDocument>.Projection.Exclude("Id"))
.FirstOrDefault();
var filter = Builders<BsonDocument>.Filter.Eq("_id", s.GetValue("_id"));
var updateRouteId = Builders<BsonDocument>.Update.Set("RouteId", routeId);
var updateRoute = Builders<BsonDocument>.Update.Set("Route", route);
Schedules.UpdateOneAsync(filter, updateRouteId);
Schedules.UpdateOneAsync(filter, updateRoute);
});
// Убираем поле "Id"
var update = Builders<BsonDocument>.Update.Unset("Id");
Drivers.UpdateMany(new BsonDocument(), update);
Transport.UpdateMany(new BsonDocument(), update);
Routes.UpdateMany(new BsonDocument(), update);
Stops.UpdateMany(new BsonDocument(), update);
Schedules.UpdateMany(new BsonDocument(), update);
// Удаление коллекции для связи сущностей "Маршруты" и "Остановки"
RouteStops.Database.DropCollection("RouteStops");
}
/// <summary>
/// Перенос данных из таблицы в коллекцию
/// </summary>
/// <param name="collectionName"></param>
private void Transfer(string collectionName)
{
using var connection = new NpgsqlConnection(_pgsqlDBConnectionString);
connection.Open();
using var command = new NpgsqlCommand($"SELECT * FROM \"{collectionName}\"", connection);
using var reader = command.ExecuteReader();
var collection = _database.GetCollection<BsonDocument>(collectionName);
while (reader.Read())
{
var document = new BsonDocument();
for (int i = 0; i < reader.FieldCount; i++)
{
string fieldName = reader.GetName(i);
object value = reader.GetValue(i);
document.Add(fieldName, BsonValue.Create(value));
}
collection.InsertOne(document);
}
reader.Close();
command.Cancel();
connection.Close();
}
}
}

View File

@ -0,0 +1,222 @@
using MongoDB.Driver;
using MongoDB.Bson;
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.SearchModels;
using RouteGuideContracts.StoragesContracts;
using RouteGuideContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RouteGuideMongoDBImplement.Models;
namespace RouteGuideMongoDBImplement.Implements
{
/// <summary>
/// Хранилище для сущности "Водитель"
/// </summary>
public class DriverStorage : IDriverStorage
{
/// <summary>
/// Получение полного списка
/// </summary>
/// <returns></returns>
public List<DriverViewModel> GetFullList()
{
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Driver>.Filter;
var filter = filterBuilder.Empty;
return context.Drivers
.Find(filter)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение фильтрованного списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<DriverViewModel> GetFilteredList(DriverSearchModel model)
{
if (string.IsNullOrEmpty(model.Phone))
{
return new();
}
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Driver>.Filter;
var filter = filterBuilder.Eq(x => x.Phone, model.Phone);
return context.Drivers
.Find(filter)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получить список из заданного количества элементов
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
public List<DriverViewModel> GetList(int count)
{
if (count <= 0)
{
return new();
}
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Driver>.Filter;
var filter = filterBuilder.Empty;
return context.Drivers
.Find(filter)
.Limit(count)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DriverViewModel? GetElement(DriverSearchModel model)
{
if (string.IsNullOrEmpty(model.Id?.ToString()) && string.IsNullOrEmpty(model.Phone))
{
return null;
}
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Driver>.Filter;
var filter = filterBuilder.Empty;
if (!string.IsNullOrEmpty(model.Phone))
{
filter &= filterBuilder.Eq(x => x.Phone, model.Phone);
}
if (!string.IsNullOrEmpty(model.Id?.ToString()))
{
filter &= filterBuilder.Eq(x => x.Id, model.Id);
}
return context.Drivers
.Find(filter)
.FirstOrDefault()
?.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.InsertOne(newDriver);
return newDriver.GetViewModel;
}
/// <summary>
/// Редактирование элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DriverViewModel? Update(DriverBindingModel model)
{
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Driver>.Filter;
var filter = filterBuilder.Eq(x => x.Id, model.Id);
var driver = context.Drivers.Find(filter).FirstOrDefault();
if (driver == null)
{
return null;
}
driver.Update(model);
context.Drivers.ReplaceOne(filter, driver);
return driver.GetViewModel;
}
/// <summary>
/// Удаление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DriverViewModel? Delete(DriverBindingModel model)
{
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Driver>.Filter;
var filter = filterBuilder.Eq(x => x.Id, model.Id);
var driver = context.Drivers.Find(filter).FirstOrDefault();
if (driver == null)
{
return null;
}
context.Drivers.FindOneAndDelete(filter);
return driver.GetViewModel;
}
/// <summary>
/// Удаление записи
/// </summary>
/// <returns></returns>
public DriverViewModel? Delete()
{
if (!GetFullList().Any())
{
return null;
}
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Driver>.Filter;
var filter = filterBuilder.Empty;
var element = context.Drivers.FindOneAndDelete(filter);
return element.GetViewModel;
}
/// <summary>
/// Удаление всех элементов
/// </summary>
/// <returns></returns>
public int Clear()
{
using var context = new RouteGuideDatabase();
int count = GetFullList().Count;
if (count <= 0)
{
return 0;
}
var filterBuilder = Builders<Driver>.Filter;
var filter = filterBuilder.Empty;
context.Drivers.DeleteMany(filter);
return count;
}
}
}

View File

@ -0,0 +1,222 @@
using MongoDB.Driver;
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.SearchModels;
using RouteGuideContracts.StoragesContracts;
using RouteGuideContracts.ViewModels;
using RouteGuideMongoDBImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RouteGuideMongoDBImplement.Implements
{
/// <summary>
/// Хранилище для сущности "Маршрут"
/// </summary>
public class RouteStorage : IRouteStorage
{
/// <summary>
/// Получение полного списка
/// </summary>
/// <returns></returns>
public List<RouteViewModel> GetFullList()
{
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Route>.Filter;
var filter = filterBuilder.Empty;
return context.Routes
.Find(filter)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение фильтрованного списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<RouteViewModel> GetFilteredList(RouteSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Route>.Filter;
var filter = filterBuilder.Eq(x => x.Name, model.Name);
return context.Routes
.Find(filter)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получить список из заданного количества элементов
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
public List<RouteViewModel> GetList(int count)
{
if (count <= 0)
{
return new();
}
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Route>.Filter;
var filter = filterBuilder.Empty;
return context.Routes
.Find(filter)
.Limit(count)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public RouteViewModel? GetElement(RouteSearchModel model)
{
if (string.IsNullOrEmpty(model.Id?.ToString()) && string.IsNullOrEmpty(model.Name))
{
return null;
}
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Route>.Filter;
var filter = filterBuilder.Empty;
if (!string.IsNullOrEmpty(model.Name))
{
filter &= filterBuilder.Eq(x => x.Name, model.Name);
}
if (!string.IsNullOrEmpty(model.Id?.ToString()))
{
filter &= filterBuilder.Eq(x => x.Id, model.Id);
}
return context.Routes
.Find(filter)
.FirstOrDefault()
?.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.InsertOne(newRoute);
return newRoute.GetViewModel;
}
/// <summary>
/// Редактирование элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public RouteViewModel? Update(RouteBindingModel model)
{
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Route>.Filter;
var filter = filterBuilder.Eq(x => x.Id, model.Id.ToString());
var route = context.Routes.Find(filter).FirstOrDefault();
if (route == null)
{
return null;
}
route.Update(model);
route.UpdateStops(context, model);
context.Routes.ReplaceOne(filter, route);
return route.GetViewModel;
}
/// <summary>
/// Удаление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public RouteViewModel? Delete(RouteBindingModel model)
{
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Route>.Filter;
var filter = filterBuilder.Eq(x => x.Id, model.Id);
var route = context.Routes.Find(filter).FirstOrDefault();
if (route == null)
{
return null;
}
context.Routes.FindOneAndDelete(filter);
return route.GetViewModel;
}
/// <summary>
/// Удаление записи
/// </summary>
/// <returns></returns>
public RouteViewModel? Delete()
{
if (!GetFullList().Any())
{
return null;
}
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Route>.Filter;
var filter = filterBuilder.Empty;
var element = context.Routes.FindOneAndDelete(filter);
return element.GetViewModel;
}
/// <summary>
/// Удаление всех элементов
/// </summary>
/// <returns></returns>
public int Clear()
{
using var context = new RouteGuideDatabase();
int count = GetFullList().Count;
if (count <= 0)
{
return 0;
}
var filterBuilder = Builders<Route>.Filter;
var filter = filterBuilder.Empty;
context.Routes.DeleteMany(filter);
return count;
}
}
}

View File

@ -0,0 +1,213 @@
using MongoDB.Driver;
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.SearchModels;
using RouteGuideContracts.StoragesContracts;
using RouteGuideContracts.ViewModels;
using RouteGuideMongoDBImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RouteGuideMongoDBImplement.Implements
{
/// <summary>
/// Хранилище для сущности "Расписание"
/// </summary>
public class ScheduleStorage : IScheduleStorage
{
/// <summary>
/// Получение полного списка
/// </summary>
/// <returns></returns>
public List<ScheduleViewModel> GetFullList()
{
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Schedule>.Filter;
var filter = filterBuilder.Empty;
return context.Schedules
.Find(filter)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение фильтрованного списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<ScheduleViewModel> GetFilteredList(ScheduleSearchModel model)
{
if (string.IsNullOrEmpty(model.Id?.ToString()))
{
return new();
}
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Schedule>.Filter;
var filter = filterBuilder.Eq(x => x.Id, model.Id);
return context.Schedules
.Find(filter)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получить список из заданного количества элементов
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
public List<ScheduleViewModel> GetList(int count)
{
if (count <= 0)
{
return new();
}
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Schedule>.Filter;
var filter = filterBuilder.Empty;
return context.Schedules
.Find(filter)
.Limit(count)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ScheduleViewModel? GetElement(ScheduleSearchModel model)
{
if (string.IsNullOrEmpty(model.Id?.ToString()))
{
return null;
}
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Schedule>.Filter;
var filter = filterBuilder.Eq(x => x.Id, model.Id);
return context.Schedules
.Find(filter)
.FirstOrDefault()
?.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.InsertOne(newSchedule);
return newSchedule.GetViewModel;
}
/// <summary>
/// Редактирование элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ScheduleViewModel? Update(ScheduleBindingModel model)
{
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Schedule>.Filter;
var filter = filterBuilder.Eq(x => x.Id, model.Id);
var schedule = context.Schedules.Find(filter).FirstOrDefault();
if (schedule == null)
{
return null;
}
schedule.Update(model);
context.Schedules.ReplaceOne(filter, schedule);
return schedule.GetViewModel;
}
/// <summary>
/// Удаление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ScheduleViewModel? Delete(ScheduleBindingModel model)
{
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Schedule>.Filter;
var filter = filterBuilder.Eq(x => x.Id, model.Id);
var schedule = context.Schedules.Find(filter).FirstOrDefault();
if (schedule == null)
{
return null;
}
context.Schedules.FindOneAndDelete(filter);
return schedule.GetViewModel;
}
/// <summary>
/// Удаление записи
/// </summary>
/// <returns></returns>
public ScheduleViewModel? Delete()
{
if (!GetFullList().Any())
{
return null;
}
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Schedule>.Filter;
var filter = filterBuilder.Empty;
var element = context.Schedules.FindOneAndDelete(filter);
return element.GetViewModel;
}
/// <summary>
/// Удаление всех элементов
/// </summary>
/// <returns></returns>
public int Clear()
{
using var context = new RouteGuideDatabase();
int count = GetFullList().Count;
if (count <= 0)
{
return 0;
}
var filterBuilder = Builders<Schedule>.Filter;
var filter = filterBuilder.Empty;
context.Schedules.DeleteMany(filter);
return count;
}
}
}

View File

@ -0,0 +1,221 @@
using MongoDB.Driver;
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.SearchModels;
using RouteGuideContracts.StoragesContracts;
using RouteGuideContracts.ViewModels;
using RouteGuideMongoDBImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RouteGuideMongoDBImplement.Implements
{
/// <summary>
/// Хранилище для сущности "Остановка"
/// </summary>
public class StopStorage : IStopStorage
{
/// <summary>
/// Получение полного списка
/// </summary>
/// <returns></returns>
public List<StopViewModel> GetFullList()
{
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Stop>.Filter;
var filter = filterBuilder.Empty;
return context.Stops
.Find(filter)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение фильтрованного списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<StopViewModel> GetFilteredList(StopSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Stop>.Filter;
var filter = filterBuilder.Eq(x => x.Name, model.Name);
return context.Stops
.Find(filter)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получить список из заданного количества элементов
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
public List<StopViewModel> GetList(int count)
{
if (count <= 0)
{
return new();
}
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Stop>.Filter;
var filter = filterBuilder.Empty;
return context.Stops
.Find(filter)
.Limit(count)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public StopViewModel? GetElement(StopSearchModel model)
{
if (string.IsNullOrEmpty(model.Id?.ToString()) && string.IsNullOrEmpty(model.Name))
{
return null;
}
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Stop>.Filter;
var filter = filterBuilder.Empty;
if (!string.IsNullOrEmpty(model.Name))
{
filter &= filterBuilder.Eq(x => x.Name, model.Name);
}
if (!string.IsNullOrEmpty(model.Id?.ToString()))
{
filter &= filterBuilder.Eq(x => x.Id, model.Id);
}
return context.Stops
.Find(filter)
.FirstOrDefault()
?.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.InsertOne(newStop);
return newStop.GetViewModel;
}
/// <summary>
/// Редактирование элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public StopViewModel? Update(StopBindingModel model)
{
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Stop>.Filter;
var filter = filterBuilder.Eq(x => x.Id, model.Id);
var stop = context.Stops.Find(filter).FirstOrDefault();
if (stop == null)
{
return null;
}
stop.Update(model);
context.Stops.ReplaceOne(filter, stop);
return stop.GetViewModel;
}
/// <summary>
/// Удаление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public StopViewModel? Delete(StopBindingModel model)
{
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Stop>.Filter;
var filter = filterBuilder.Eq(x => x.Id, model.Id);
var stop = context.Stops.Find(filter).FirstOrDefault();
if (stop == null)
{
return null;
}
context.Stops.FindOneAndDelete(filter);
return stop.GetViewModel;
}
/// <summary>
/// Удаление записи
/// </summary>
/// <returns></returns>
public StopViewModel? Delete()
{
if (!GetFullList().Any())
{
return null;
}
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Stop>.Filter;
var filter = filterBuilder.Empty;
var element = context.Stops.FindOneAndDelete(filter);
return element.GetViewModel;
}
/// <summary>
/// Удаление всех элементов
/// </summary>
/// <returns></returns>
public int Clear()
{
using var context = new RouteGuideDatabase();
int count = GetFullList().Count;
if (count <= 0)
{
return 0;
}
var filterBuilder = Builders<Stop>.Filter;
var filter = filterBuilder.Empty;
context.Stops.DeleteMany(filter);
return count;
}
}
}

View File

@ -0,0 +1,221 @@
using MongoDB.Driver;
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.SearchModels;
using RouteGuideContracts.StoragesContracts;
using RouteGuideContracts.ViewModels;
using RouteGuideMongoDBImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RouteGuideMongoDBImplement.Implements
{
/// <summary>
/// Хранилище для сущности "Транспорт"
/// </summary>
public class TransportStorage : ITransportStorage
{
/// <summary>
/// Получение полного списка
/// </summary>
/// <returns></returns>
public List<TransportViewModel> GetFullList()
{
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Transport>.Filter;
var filter = filterBuilder.Empty;
return context.Transport
.Find(filter)
.ToList()
.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();
var filterBuilder = Builders<Transport>.Filter;
var filter = filterBuilder.Eq(x => x.License, model.License);
return context.Transport
.Find(filter)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получить список из заданного количества элементов
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
public List<TransportViewModel> GetList(int count)
{
if (count <= 0)
{
return new();
}
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Transport>.Filter;
var filter = filterBuilder.Empty;
return context.Transport
.Find(filter)
.Limit(count)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public TransportViewModel? GetElement(TransportSearchModel model)
{
if (string.IsNullOrEmpty(model.Id?.ToString()) && string.IsNullOrEmpty(model.License))
{
return null;
}
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Transport>.Filter;
var filter = filterBuilder.Empty;
if (!string.IsNullOrEmpty(model.License))
{
filter &= filterBuilder.Eq(x => x.License, model.License);
}
if (!string.IsNullOrEmpty(model.Id?.ToString()))
{
filter &= filterBuilder.Eq(x => x.Id, model.Id);
}
return context.Transport
.Find(filter)
.FirstOrDefault()
?.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.InsertOne(newTransport);
return newTransport.GetViewModel;
}
/// <summary>
/// Редактирование элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public TransportViewModel? Update(TransportBindingModel model)
{
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Transport>.Filter;
var filter = filterBuilder.Eq(x => x.Id, model.Id);
var transport = context.Transport.Find(filter).FirstOrDefault();
if (transport == null)
{
return null;
}
transport.Update(model);
context.Transport.ReplaceOne(filter, transport);
return transport.GetViewModel;
}
/// <summary>
/// Удаление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public TransportViewModel? Delete(TransportBindingModel model)
{
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Transport>.Filter;
var filter = filterBuilder.Eq(x => x.Id, model.Id);
var transport = context.Transport.Find(filter).FirstOrDefault();
if (transport == null)
{
return null;
}
context.Transport.FindOneAndDelete(filter);
return transport.GetViewModel;
}
/// <summary>
/// Удаление записи
/// </summary>
/// <returns></returns>
public TransportViewModel? Delete()
{
if (!GetFullList().Any())
{
return null;
}
using var context = new RouteGuideDatabase();
var filterBuilder = Builders<Transport>.Filter;
var filter = filterBuilder.Empty;
var element = context.Transport.FindOneAndDelete(filter);
return element.GetViewModel;
}
/// <summary>
/// Удаление всех элементов
/// </summary>
/// <returns></returns>
public int Clear()
{
using var context = new RouteGuideDatabase();
int count = GetFullList().Count;
if (count <= 0)
{
return 0;
}
var filterBuilder = Builders<Transport>.Filter;
var filter = filterBuilder.Empty;
context.Transport.DeleteMany(filter);
return count;
}
}
}

View File

@ -0,0 +1,113 @@
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson;
using RouteGuideDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.ViewModels;
namespace RouteGuideMongoDBImplement.Models
{
/// <summary>
/// Сущность "Водитель"
/// </summary>
public class Driver : IDriverModel<string>
{
/// <summary>
/// Идентификатор
/// </summary>
[BsonId]
[BsonElement("_id")]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; private set; }
/// <summary>
/// ФИО водителя
/// </summary>
[BsonRequired]
public string FullName { get; private set; } = string.Empty;
/// <summary>
/// Номер телефона водителя
/// </summary>
[BsonRequired]
public string Phone { get; private set; } = string.Empty;
/// <summary>
/// Опыт работы водителя
/// </summary>
[BsonIgnoreIfNull]
[BsonIgnoreIfDefault]
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()
{
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()
{
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,150 @@
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson;
using RouteGuideDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.ViewModels;
using MongoDB.Driver;
namespace RouteGuideMongoDBImplement.Models
{
/// <summary>
/// Сущность "Маршрут"
/// </summary>
public class Route : IRouteModel<string>
{
/// <summary>
/// Идентификатор
/// </summary>
[BsonId]
[BsonElement("_id")]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; private set; }
/// <summary>
/// Название маршрута
/// </summary>
[BsonRequired]
public string Name { get; private set; } = string.Empty;
/// <summary>
/// Идентификатор транспорта
/// </summary>
[BsonRequired]
[BsonElement("TransportId")]
public string? TransportId { get; private set; }
/// <summary>
/// Сущность "Транспорт"
/// </summary>
[BsonIgnoreIfNull]
[BsonIgnoreIfDefault]
public virtual Transport Transport { get; private set; } = new();
/// <summary>
/// Коллекция остановок маршрута
/// </summary>
[BsonElement("Stops")]
public Dictionary<string, (Stop Stop, int Number)>? Stops = new();
/// <summary>
/// Коллекция остановок маршрута
/// </summary>
[BsonIgnore]
private Dictionary<string, (IStopModel<string>, int)>? _routeStops = null;
/// <summary>
/// Коллекция остановок маршрута
/// </summary>
[BsonIgnore]
public Dictionary<string, (IStopModel<string>, int)>? RouteStops
{
get
{
if (_routeStops == null)
{
_routeStops = Stops?
.ToDictionary(recRS => recRS.Key, recRS => (recRS.Value.Stop as IStopModel<string>, recRS.Value.Number));
}
return _routeStops;
}
}
/// <summary>
/// Созданме модели
/// </summary>
/// <param name="context"></param>
/// <param name="model"></param>
/// <returns></returns>
public static Route Create(RouteGuideDatabase context, RouteBindingModel model)
{
return new Route()
{
Name = model.Name,
TransportId = model.TransportId.ToString(),
Transport = context.Transport
.Find(Builders<Transport>.Filter.Eq(x => x.Id, model.TransportId))
.FirstOrDefault(),
Stops = model.RouteStops.ToDictionary(
x => x.Key.ToString()!,
x => (context.Stops
.Find(Builders<Stop>.Filter.Eq(y => y.Id, x.Key))
.FirstOrDefault(),
x.Value.Item2))
};
}
/// <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?
.ToDictionary(recRS => (object)recRS.Key, recRS => (new StopViewModel()
{
Id = (object)recRS.Value.Item1.Id!,
Name = recRS.Value.Item1.Name,
Street = recRS.Value.Item1.Street,
Number = recRS.Value.Item1.Number
} as IStopModel<object>, recRS.Value.Item2)) ?? new(),
TransportLicense = Transport.License
};
/// <summary>
/// Обновление списка связей
/// </summary>
/// <param name="context"></param>
/// <param name="model"></param>
public void UpdateStops(RouteGuideDatabase context, RouteBindingModel model)
{
Stops = model.RouteStops.ToDictionary(
x => x.Key.ToString()!,
x => (context.Stops
.Find(Builders<Stop>.Filter.Eq(y => y.Id, x.Key))
.FirstOrDefault(),
x.Value.Item2));
_routeStops = null;
}
}
}

View File

@ -0,0 +1,122 @@
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson;
using RouteGuideDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.ViewModels;
using MongoDB.Driver;
namespace RouteGuideMongoDBImplement.Models
{
/// <summary>
/// Сущность "Расписание"
/// </summary>
public class Schedule : IScheduleModel<string>
{
/// <summary>
/// Идентификатор
/// </summary>
[BsonId]
[BsonElement("_id")]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; private set; }
/// <summary>
/// Дата записи расписания
/// </summary>
[BsonRequired]
public DateTime Date { get; private set; } = DateTime.Now;
/// <summary>
/// Время отправления
/// </summary>
[BsonRequired]
public DateTime DepartureTime { get; private set; } = DateTime.MinValue;
/// <summary>
/// Время прибытия
/// </summary>
[BsonRequired]
public DateTime ArrivalTime { get; private set; } = DateTime.MinValue;
/// <summary>
/// Периодичность движения транспорта
/// </summary>
[BsonRequired]
public DateTime Frequency { get; private set; } = DateTime.MinValue;
/// <summary>
/// Идентификатор маршрута
/// </summary>
[BsonRequired]
[BsonElement("RouteId")]
public string? RouteId { get; private set; }
/// <summary>
/// Сущность "Маршрут"
/// </summary>
[BsonIgnoreIfNull]
[BsonIgnoreIfDefault]
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()
{
Date = model.Date,
DepartureTime = model.DepartureTime,
ArrivalTime = model.ArrivalTime,
Frequency = model.Frequency,
RouteId = model.RouteId.ToString(),
Route = context.Routes
.Find(Builders<Route>.Filter.Eq(x => x.Id, model.RouteId))
.FirstOrDefault()
};
}
/// <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!,
RouteName = Route.Name
};
}
}

View File

@ -0,0 +1,112 @@
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson;
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.ViewModels;
using RouteGuideDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RouteGuideMongoDBImplement.Models
{
/// <summary>
/// Сущность "Остановка"
/// </summary>
public class Stop : IStopModel<string>
{
/// <summary>
/// Идентификатор
/// </summary>
[BsonId]
[BsonElement("_id")]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; private set; }
/// <summary>
/// Название остановки
/// </summary>
[BsonRequired]
public string Name { get; private set; } = string.Empty;
/// <summary>
/// Название улицы
/// </summary>
[BsonRequired]
public string Street { get; private set; } = string.Empty;
/// <summary>
/// Номер дома
/// </summary>
[BsonRequired]
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()
{
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()
{
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,113 @@
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.ViewModels;
using RouteGuideDataModels.Enums;
using RouteGuideDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson;
using MongoDB.Driver;
namespace RouteGuideMongoDBImplement.Models
{
/// <summary>
/// Сущность "Транспорт"
/// </summary>
public class Transport : ITransportModel<string>
{
/// <summary>
/// Идентификатор
/// </summary>
[BsonId]
[BsonElement("_id")]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; private set; }
/// <summary>
/// Номерной знак
/// </summary>
[BsonRequired]
public string License { get; private set; } = string.Empty;
/// <summary>
/// Тип транспортного средства
/// </summary>
[BsonRequired]
public TransportType Type { get; private set; } = TransportType.Автобус;
/// <summary>
/// Вместимость (количество пассажиров)
/// </summary>
[BsonRequired]
public int Capacity { get; private set; }
/// <summary>
/// Идентификатор водителя
/// </summary>
[BsonRequired]
[BsonElement("DriverId")]
public string? DriverId { get; private set; }
/// <summary>
/// Сущность "Водитель"
/// </summary>
[BsonIgnoreIfNull]
[BsonIgnoreIfDefault]
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()
{
License = model.License,
Type = model.Type,
Capacity = model.Capacity,
DriverId = model.DriverId.ToString(),
Driver = context.Drivers
.Find(Builders<Driver>.Filter.Eq(x => x.Id, model.DriverId))
.FirstOrDefault()
};
}
/// <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,
Capacity = Capacity,
DriverId = DriverId!,
DriverName = Driver.FullName
};
}
}

View File

@ -0,0 +1,68 @@
using MongoDB.Driver;
using RouteGuideMongoDBImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RouteGuideMongoDBImplement
{
/// <summary>
/// Класс для взаимодействия с базой данных
/// </summary>
public class RouteGuideDatabase : IDisposable
{
/// <summary>
/// Клиент
/// </summary>
public readonly MongoClient _client;
/// <summary>
/// База данных
/// </summary>
private readonly IMongoDatabase _database;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="connectionString">Параметры подключения к базе данных</param>
/// <param name="databaseName">Название базы данных</param>
public RouteGuideDatabase(string connectionString = "mongodb://localhost:27017",
string databaseName = "RouteGuideDatabase")
{
_client = new MongoClient(connectionString);
_database = _client.GetDatabase(databaseName);
}
/// <summary>
/// Коллекция "Водители"
/// </summary>
public IMongoCollection<Driver> Drivers => _database.GetCollection<Driver>("Drivers");
/// <summary>
/// Коллекция "Транспорт"
/// </summary>
public IMongoCollection<Transport> Transport => _database.GetCollection<Transport>("Transport");
/// <summary>
/// Коллекция "Маршруты"
/// </summary>
public IMongoCollection<Route> Routes => _database.GetCollection<Route>("Routes");
/// <summary>
/// Коллекция "Остановки"
/// </summary>
public IMongoCollection<Stop> Stops => _database.GetCollection<Stop>("Stops");
/// <summary>
/// Коллекция "Расписания"
/// </summary>
public IMongoCollection<Schedule> Schedules => _database.GetCollection<Schedule>("Schedules");
/// <summary>
/// Освободить ресурсы
/// </summary>
public void Dispose() { }
}
}

View File

@ -0,0 +1,20 @@
<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="MongoDB.Bson" Version="2.25.0" />
<PackageReference Include="MongoDB.Driver" Version="2.25.0" />
<PackageReference Include="Npgsql" Version="7.0.4" />
</ItemGroup>
</Project>

View File

@ -31,12 +31,12 @@ namespace RouteGuideView
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
private int? _id; private object? _id;
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
public int Id { set { _id = value; } } public object Id { set { _id = value; } }
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@ -55,7 +55,7 @@ namespace RouteGuideView
/// <param name="e"></param> /// <param name="e"></param>
private void FormDriver_Load(object sender, EventArgs e) private void FormDriver_Load(object sender, EventArgs e)
{ {
if (!_id.HasValue) if (_id == null)
{ {
return; return;
} }
@ -65,7 +65,7 @@ namespace RouteGuideView
_logger.LogInformation("Получение сущности 'Водитель'"); _logger.LogInformation("Получение сущности 'Водитель'");
var view = _driverLogic.ReadElement(new DriverSearchModel var view = _driverLogic.ReadElement(new DriverSearchModel
{ {
Id = _id.Value Id = _id
}); });
if (view != null) if (view != null)
{ {
@ -104,13 +104,13 @@ namespace RouteGuideView
{ {
var model = new DriverBindingModel var model = new DriverBindingModel
{ {
Id = _id ?? 0, Id = _id,
FullName = textBoxFullName.Text, FullName = textBoxFullName.Text,
Phone = textBoxPhone.Text, Phone = textBoxPhone.Text,
Experience = int.TryParse(textBoxExperience.Text, out int experience) ? experience : 0 Experience = int.TryParse(textBoxExperience.Text, out int experience) ? experience : 0
}; };
var operationResult = _id.HasValue ? _driverLogic.Update(model) : _driverLogic.Create(model); var operationResult = _id != null ? _driverLogic.Update(model) : _driverLogic.Create(model);
if (!operationResult) if (!operationResult)
{ {
throw new Exception("Ошибка при сохранении сущности 'Водитель'. Дополнительная информация в логах."); throw new Exception("Ошибка при сохранении сущности 'Водитель'. Дополнительная информация в логах.");

View File

@ -75,7 +75,7 @@ namespace RouteGuideView
var service = Program.ServiceProvider?.GetService(typeof(FormDriver)); var service = Program.ServiceProvider?.GetService(typeof(FormDriver));
if (service is FormDriver form) if (service is FormDriver form)
{ {
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); form.Id = dataGridView.SelectedRows[0].Cells["Id"].Value;
if (form.ShowDialog() == DialogResult.OK) if (form.ShowDialog() == DialogResult.OK)
{ {
LoadData(); LoadData();
@ -95,7 +95,7 @@ namespace RouteGuideView
{ {
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); object id = dataGridView.SelectedRows[0].Cells["Id"].Value;
_logger.LogInformation("Удаление сущности 'Водитель'"); _logger.LogInformation("Удаление сущности 'Водитель'");
try try

View File

@ -20,203 +20,215 @@
base.Dispose(disposing); base.Dispose(disposing);
} }
#region Windows Form Designer generated code #region Windows Form Designer generated code
/// <summary> /// <summary>
/// Required method for Designer support - do not modify /// Required method for Designer support - do not modify
/// the contents of this method with the code editor. /// the contents of this method with the code editor.
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
menuStrip1 = new MenuStrip(); menuStrip1 = new MenuStrip();
справочникиToolStripMenuItem = new ToolStripMenuItem(); справочникиToolStripMenuItem = new ToolStripMenuItem();
DrviversToolStripMenuItem = new ToolStripMenuItem(); DrviversToolStripMenuItem = new ToolStripMenuItem();
TransportToolStripMenuItem = new ToolStripMenuItem(); TransportToolStripMenuItem = new ToolStripMenuItem();
RoutesToolStripMenuItem = new ToolStripMenuItem(); RoutesToolStripMenuItem = new ToolStripMenuItem();
StopsToolStripMenuItem = new ToolStripMenuItem(); StopsToolStripMenuItem = new ToolStripMenuItem();
тестыToolStripMenuItem = new ToolStripMenuItem(); тестыToolStripMenuItem = new ToolStripMenuItem();
DriversTestsToolStripMenuItem = new ToolStripMenuItem(); DriversTestsToolStripMenuItem = new ToolStripMenuItem();
TransportTestsToolStripMenuItem = new ToolStripMenuItem(); TransportTestsToolStripMenuItem = new ToolStripMenuItem();
RoutesTestsToolStripMenuItem = new ToolStripMenuItem(); RoutesTestsToolStripMenuItem = new ToolStripMenuItem();
StopsTestsToolStripMenuItem = new ToolStripMenuItem(); StopsTestsToolStripMenuItem = new ToolStripMenuItem();
SchedulesTestsToolStripMenuItem = new ToolStripMenuItem(); SchedulesTestsToolStripMenuItem = new ToolStripMenuItem();
buttonCreate = new Button(); buttonCreate = new Button();
buttonUpdate = new Button(); buttonUpdate = new Button();
buttonDelete = new Button(); buttonDelete = new Button();
buttonRefresh = new Button(); buttonRefresh = new Button();
dataGridView = new DataGridView(); dataGridView = new DataGridView();
menuStrip1.SuspendLayout(); buttonSyncData = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); menuStrip1.SuspendLayout();
SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
// SuspendLayout();
// menuStrip1 //
// // menuStrip1
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, тестыToolStripMenuItem }); //
menuStrip1.Location = new Point(0, 0); menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, тестыToolStripMenuItem });
menuStrip1.Name = "menuStrip1"; menuStrip1.Location = new Point(0, 0);
menuStrip1.Size = new Size(984, 24); menuStrip1.Name = "menuStrip1";
menuStrip1.TabIndex = 0; menuStrip1.Size = new Size(984, 24);
menuStrip1.Text = "menuStrip1"; menuStrip1.TabIndex = 0;
// menuStrip1.Text = "menuStrip1";
// справочникиToolStripMenuItem //
// // справочникиToolStripMenuItem
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DrviversToolStripMenuItem, TransportToolStripMenuItem, RoutesToolStripMenuItem, StopsToolStripMenuItem }); //
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DrviversToolStripMenuItem, TransportToolStripMenuItem, RoutesToolStripMenuItem, StopsToolStripMenuItem });
справочникиToolStripMenuItem.Size = new Size(97, 20); справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Text = " Справочники"; справочникиToolStripMenuItem.Size = new Size(97, 20);
// справочникиToolStripMenuItem.Text = " Справочники";
// DrviversToolStripMenuItem //
// // DrviversToolStripMenuItem
DrviversToolStripMenuItem.Name = "DrviversToolStripMenuItem"; //
DrviversToolStripMenuItem.Size = new Size(136, 22); DrviversToolStripMenuItem.Name = "DrviversToolStripMenuItem";
DrviversToolStripMenuItem.Text = "Водители"; DrviversToolStripMenuItem.Size = new Size(136, 22);
DrviversToolStripMenuItem.Click += DrviversToolStripMenuItem_Click; DrviversToolStripMenuItem.Text = "Водители";
// DrviversToolStripMenuItem.Click += DrviversToolStripMenuItem_Click;
// TransportToolStripMenuItem //
// // TransportToolStripMenuItem
TransportToolStripMenuItem.Name = "TransportToolStripMenuItem"; //
TransportToolStripMenuItem.Size = new Size(136, 22); TransportToolStripMenuItem.Name = "TransportToolStripMenuItem";
TransportToolStripMenuItem.Text = "Транспорт"; TransportToolStripMenuItem.Size = new Size(136, 22);
TransportToolStripMenuItem.Click += TransportToolStripMenuItem_Click; TransportToolStripMenuItem.Text = "Транспорт";
// TransportToolStripMenuItem.Click += TransportToolStripMenuItem_Click;
// RoutesToolStripMenuItem //
// // RoutesToolStripMenuItem
RoutesToolStripMenuItem.Name = "RoutesToolStripMenuItem"; //
RoutesToolStripMenuItem.Size = new Size(136, 22); RoutesToolStripMenuItem.Name = "RoutesToolStripMenuItem";
RoutesToolStripMenuItem.Text = "Маршруты"; RoutesToolStripMenuItem.Size = new Size(136, 22);
RoutesToolStripMenuItem.Click += RoutesToolStripMenuItem_Click; RoutesToolStripMenuItem.Text = "Маршруты";
// RoutesToolStripMenuItem.Click += RoutesToolStripMenuItem_Click;
// StopsToolStripMenuItem //
// // StopsToolStripMenuItem
StopsToolStripMenuItem.Name = "StopsToolStripMenuItem"; //
StopsToolStripMenuItem.Size = new Size(136, 22); StopsToolStripMenuItem.Name = "StopsToolStripMenuItem";
StopsToolStripMenuItem.Text = "Остановки"; StopsToolStripMenuItem.Size = new Size(136, 22);
StopsToolStripMenuItem.Click += StopsToolStripMenuItem_Click; StopsToolStripMenuItem.Text = "Остановки";
// StopsToolStripMenuItem.Click += StopsToolStripMenuItem_Click;
// тестыToolStripMenuItem //
// // тестыToolStripMenuItem
тестыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DriversTestsToolStripMenuItem, TransportTestsToolStripMenuItem, RoutesTestsToolStripMenuItem, StopsTestsToolStripMenuItem, SchedulesTestsToolStripMenuItem }); //
тестыToolStripMenuItem.Name = естыToolStripMenuItem"; тестыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DriversTestsToolStripMenuItem, TransportTestsToolStripMenuItem, RoutesTestsToolStripMenuItem, StopsTestsToolStripMenuItem, SchedulesTestsToolStripMenuItem });
тестыToolStripMenuItem.Size = new Size(51, 20); тестыToolStripMenuItem.Name = естыToolStripMenuItem";
тестыToolStripMenuItem.Text = "Тесты"; тестыToolStripMenuItem.Size = new Size(51, 20);
// тестыToolStripMenuItem.Text = "Тесты";
// DriversTestsToolStripMenuItem //
// // DriversTestsToolStripMenuItem
DriversTestsToolStripMenuItem.Name = "DriversTestsToolStripMenuItem"; //
DriversTestsToolStripMenuItem.Size = new Size(180, 22); DriversTestsToolStripMenuItem.Name = "DriversTestsToolStripMenuItem";
DriversTestsToolStripMenuItem.Text = "Водители"; DriversTestsToolStripMenuItem.Size = new Size(139, 22);
DriversTestsToolStripMenuItem.Click += DriversTestsToolStripMenuItem_Click; DriversTestsToolStripMenuItem.Text = "Водители";
// DriversTestsToolStripMenuItem.Click += DriversTestsToolStripMenuItem_Click;
// TransportTestsToolStripMenuItem //
// // TransportTestsToolStripMenuItem
TransportTestsToolStripMenuItem.Name = "TransportTestsToolStripMenuItem"; //
TransportTestsToolStripMenuItem.Size = new Size(180, 22); TransportTestsToolStripMenuItem.Name = "TransportTestsToolStripMenuItem";
TransportTestsToolStripMenuItem.Text = "Транспорт"; TransportTestsToolStripMenuItem.Size = new Size(139, 22);
TransportTestsToolStripMenuItem.Click += TransportTestsToolStripMenuItem_Click; TransportTestsToolStripMenuItem.Text = "Транспорт";
// TransportTestsToolStripMenuItem.Click += TransportTestsToolStripMenuItem_Click;
// RoutesTestsToolStripMenuItem //
// // RoutesTestsToolStripMenuItem
RoutesTestsToolStripMenuItem.Name = "RoutesTestsToolStripMenuItem"; //
RoutesTestsToolStripMenuItem.Size = new Size(180, 22); RoutesTestsToolStripMenuItem.Name = "RoutesTestsToolStripMenuItem";
RoutesTestsToolStripMenuItem.Text = "Маршруты"; RoutesTestsToolStripMenuItem.Size = new Size(139, 22);
RoutesTestsToolStripMenuItem.Click += RoutesTestsToolStripMenuItem_Click; RoutesTestsToolStripMenuItem.Text = "Маршруты";
// RoutesTestsToolStripMenuItem.Click += RoutesTestsToolStripMenuItem_Click;
// StopsTestsToolStripMenuItem //
// // StopsTestsToolStripMenuItem
StopsTestsToolStripMenuItem.Name = "StopsTestsToolStripMenuItem"; //
StopsTestsToolStripMenuItem.Size = new Size(180, 22); StopsTestsToolStripMenuItem.Name = "StopsTestsToolStripMenuItem";
StopsTestsToolStripMenuItem.Text = "Остановки"; StopsTestsToolStripMenuItem.Size = new Size(139, 22);
StopsTestsToolStripMenuItem.Click += StopsTestsToolStripMenuItem_Click; StopsTestsToolStripMenuItem.Text = "Остановки";
// StopsTestsToolStripMenuItem.Click += StopsTestsToolStripMenuItem_Click;
// SchedulesTestsToolStripMenuItem //
// // SchedulesTestsToolStripMenuItem
SchedulesTestsToolStripMenuItem.Name = "SchedulesTestsToolStripMenuItem"; //
SchedulesTestsToolStripMenuItem.Size = new Size(180, 22); SchedulesTestsToolStripMenuItem.Name = "SchedulesTestsToolStripMenuItem";
SchedulesTestsToolStripMenuItem.Text = "Расписания"; SchedulesTestsToolStripMenuItem.Size = new Size(139, 22);
SchedulesTestsToolStripMenuItem.Click += SchedulesTestsToolStripMenuItem_Click; SchedulesTestsToolStripMenuItem.Text = "Расписания";
// SchedulesTestsToolStripMenuItem.Click += SchedulesTestsToolStripMenuItem_Click;
// buttonCreate //
// // buttonCreate
buttonCreate.Location = new Point(885, 37); //
buttonCreate.Name = "buttonCreate"; buttonCreate.Location = new Point(885, 37);
buttonCreate.Size = new Size(75, 23); buttonCreate.Name = "buttonCreate";
buttonCreate.TabIndex = 1; buttonCreate.Size = new Size(75, 23);
buttonCreate.Text = "Создать"; buttonCreate.TabIndex = 1;
buttonCreate.UseVisualStyleBackColor = true; buttonCreate.Text = "Создать";
buttonCreate.Click += buttonCreate_Click; buttonCreate.UseVisualStyleBackColor = true;
// buttonCreate.Click += buttonCreate_Click;
// buttonUpdate //
// // buttonUpdate
buttonUpdate.Location = new Point(885, 66); //
buttonUpdate.Name = "buttonUpdate"; buttonUpdate.Location = new Point(885, 66);
buttonUpdate.Size = new Size(75, 23); buttonUpdate.Name = "buttonUpdate";
buttonUpdate.TabIndex = 2; buttonUpdate.Size = new Size(75, 23);
buttonUpdate.Text = "Изменить"; buttonUpdate.TabIndex = 2;
buttonUpdate.UseVisualStyleBackColor = true; buttonUpdate.Text = "Изменить";
buttonUpdate.Click += buttonUpdate_Click; buttonUpdate.UseVisualStyleBackColor = true;
// buttonUpdate.Click += buttonUpdate_Click;
// buttonDelete //
// // buttonDelete
buttonDelete.Location = new Point(885, 95); //
buttonDelete.Name = "buttonDelete"; buttonDelete.Location = new Point(885, 95);
buttonDelete.Size = new Size(75, 23); buttonDelete.Name = "buttonDelete";
buttonDelete.TabIndex = 3; buttonDelete.Size = new Size(75, 23);
buttonDelete.Text = "Удалить"; buttonDelete.TabIndex = 3;
buttonDelete.UseVisualStyleBackColor = true; buttonDelete.Text = "Удалить";
buttonDelete.Click += buttonDelete_Click; buttonDelete.UseVisualStyleBackColor = true;
// buttonDelete.Click += buttonDelete_Click;
// buttonRefresh //
// // buttonRefresh
buttonRefresh.Location = new Point(885, 124); //
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Location = new Point(885, 124);
buttonRefresh.Size = new Size(75, 23); buttonRefresh.Name = "buttonRefresh";
buttonRefresh.TabIndex = 4; buttonRefresh.Size = new Size(75, 23);
buttonRefresh.Text = "Обновить"; buttonRefresh.TabIndex = 4;
buttonRefresh.UseVisualStyleBackColor = true; buttonRefresh.Text = "Обновить";
buttonRefresh.Click += buttonRefresh_Click; buttonRefresh.UseVisualStyleBackColor = true;
// buttonRefresh.Click += buttonRefresh_Click;
// dataGridView //
// // dataGridView
dataGridView.AllowUserToAddRows = false; //
dataGridView.AllowUserToDeleteRows = false; dataGridView.AllowUserToAddRows = false;
dataGridView.BackgroundColor = Color.White; dataGridView.AllowUserToDeleteRows = false;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridView.BackgroundColor = Color.White;
dataGridView.Dock = DockStyle.Left; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(0, 24); dataGridView.Dock = DockStyle.Left;
dataGridView.MultiSelect = false; dataGridView.Location = new Point(0, 24);
dataGridView.Name = "dataGridView"; dataGridView.MultiSelect = false;
dataGridView.ReadOnly = true; dataGridView.Name = "dataGridView";
dataGridView.RowHeadersVisible = false; dataGridView.ReadOnly = true;
dataGridView.RowTemplate.Height = 25; dataGridView.RowHeadersVisible = false;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(850, 337); dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.TabIndex = 5; dataGridView.Size = new Size(850, 337);
// dataGridView.TabIndex = 5;
// FormMain //
// // buttonSyncData
AutoScaleDimensions = new SizeF(7F, 15F); //
AutoScaleMode = AutoScaleMode.Font; buttonSyncData.Location = new Point(885, 309);
ClientSize = new Size(984, 361); buttonSyncData.Name = "buttonSyncData";
Controls.Add(dataGridView); buttonSyncData.Size = new Size(75, 40);
Controls.Add(buttonRefresh); buttonSyncData.TabIndex = 6;
Controls.Add(buttonDelete); buttonSyncData.Text = "Синхр. данные";
Controls.Add(buttonUpdate); buttonSyncData.UseVisualStyleBackColor = true;
Controls.Add(buttonCreate); buttonSyncData.Click += buttonSyncData_Click;
Controls.Add(menuStrip1); //
MainMenuStrip = menuStrip1; // FormMain
Name = "FormMain"; //
Text = "Расписание"; AutoScaleDimensions = new SizeF(7F, 15F);
Load += FormMain_Load; AutoScaleMode = AutoScaleMode.Font;
menuStrip1.ResumeLayout(false); ClientSize = new Size(984, 361);
menuStrip1.PerformLayout(); Controls.Add(buttonSyncData);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); Controls.Add(dataGridView);
ResumeLayout(false); Controls.Add(buttonRefresh);
PerformLayout(); Controls.Add(buttonDelete);
} Controls.Add(buttonUpdate);
Controls.Add(buttonCreate);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormMain";
Text = "Расписание";
Load += FormMain_Load;
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion #endregion
private MenuStrip menuStrip1; private MenuStrip menuStrip1;
private ToolStripMenuItem справочникиToolStripMenuItem; private ToolStripMenuItem справочникиToolStripMenuItem;
private ToolStripMenuItem DrviversToolStripMenuItem; private ToolStripMenuItem DrviversToolStripMenuItem;
private ToolStripMenuItem TransportToolStripMenuItem; private ToolStripMenuItem TransportToolStripMenuItem;
@ -233,5 +245,6 @@
private ToolStripMenuItem RoutesTestsToolStripMenuItem; private ToolStripMenuItem RoutesTestsToolStripMenuItem;
private ToolStripMenuItem StopsTestsToolStripMenuItem; private ToolStripMenuItem StopsTestsToolStripMenuItem;
private ToolStripMenuItem SchedulesTestsToolStripMenuItem; private ToolStripMenuItem SchedulesTestsToolStripMenuItem;
} private Button buttonSyncData;
}
} }

View File

@ -2,273 +2,285 @@ using Microsoft.Extensions.Logging;
using RouteGuideBusinessLogics.BusinessLogics; using RouteGuideBusinessLogics.BusinessLogics;
using RouteGuideContracts.BindingModels; using RouteGuideContracts.BindingModels;
using RouteGuideContracts.BusinessLogicsContracts; using RouteGuideContracts.BusinessLogicsContracts;
using RouteGuideMongoDBImplement;
namespace RouteGuideView namespace RouteGuideView
{ {
/// <summary> /// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà ðàñïèñàíèé /// Ôîðìà äëÿ âûâîäà ñïèñêà ðàñïèñàíèé
/// </summary> /// </summary>
public partial class FormMain : Form public partial class FormMain : Form
{ {
/// <summary> /// <summary>
/// Ëîããåð /// Ëîããåð
/// </summary> /// </summary>
private readonly ILogger _logger; private readonly ILogger _logger;
/// <summary> /// <summary>
/// Áèçíåñ-ëîãèêà äëÿ ðàñïèñàíèé /// Áèçíåñ-ëîãèêà äëÿ ðàñïèñàíèé
/// </summary> /// </summary>
private readonly IScheduleLogic _schedulelogic; private readonly IScheduleLogic _schedulelogic;
/// <summary> /// <summary>
/// Êîíñòðóêòîð /// Êîíñòðóêòîð
/// </summary> /// </summary>
/// <param name="logger"></param> /// <param name="logger"></param>
/// <param name="scheduleLogic"></param> /// <param name="scheduleLogic"></param>
public FormMain(ILogger<FormMain> logger, IScheduleLogic scheduleLogic) public FormMain(ILogger<FormMain> logger, IScheduleLogic scheduleLogic)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger; _logger = logger;
_schedulelogic = scheduleLogic; _schedulelogic = scheduleLogic;
} }
/// <summary> /// <summary>
/// Çàãðóçêà äàííûõ /// Çàãðóçêà äàííûõ
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void FormMain_Load(object sender, EventArgs e) private void FormMain_Load(object sender, EventArgs e)
{ {
LoadData(); LoadData();
} }
/// <summary> /// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà âîäèòåëåé /// Ôîðìà äëÿ âûâîäà ñïèñêà âîäèòåëåé
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void DrviversToolStripMenuItem_Click(object sender, EventArgs e) private void DrviversToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormDrivers)); var service = Program.ServiceProvider?.GetService(typeof(FormDrivers));
if (service is FormDrivers form) if (service is FormDrivers form)
{ {
form.ShowDialog(); form.ShowDialog();
} }
} }
/// <summary> /// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà òðàíñïîðòà /// Ôîðìà äëÿ âûâîäà ñïèñêà òðàíñïîðòà
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void TransportToolStripMenuItem_Click(object sender, EventArgs e) private void TransportToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormTransports)); var service = Program.ServiceProvider?.GetService(typeof(FormTransports));
if (service is FormTransports form) if (service is FormTransports form)
{ {
form.ShowDialog(); form.ShowDialog();
} }
} }
/// <summary> /// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà ìàðøðóòîâ /// Ôîðìà äëÿ âûâîäà ñïèñêà ìàðøðóòîâ
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void RoutesToolStripMenuItem_Click(object sender, EventArgs e) private void RoutesToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormRoutes)); var service = Program.ServiceProvider?.GetService(typeof(FormRoutes));
if (service is FormRoutes form) if (service is FormRoutes form)
{ {
form.ShowDialog(); form.ShowDialog();
} }
} }
/// <summary> /// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà îñòàíîâîê /// Ôîðìà äëÿ âûâîäà ñïèñêà îñòàíîâîê
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void StopsToolStripMenuItem_Click(object sender, EventArgs e) private void StopsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormStops)); var service = Program.ServiceProvider?.GetService(typeof(FormStops));
if (service is FormStops form) if (service is FormStops form)
{ {
form.ShowDialog(); form.ShowDialog();
} }
} }
/// <summary> /// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Âîäèòåëü" /// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Âîäèòåëü"
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void DriversTestsToolStripMenuItem_Click(object sender, EventArgs e) private void DriversTestsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormDriversTests)); var service = Program.ServiceProvider?.GetService(typeof(FormDriversTests));
if (service is FormDriversTests form) if (service is FormDriversTests form)
{ {
form.ShowDialog(); form.ShowDialog();
} }
} }
/// <summary> /// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Òðàíñïîðò" /// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Òðàíñïîðò"
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void TransportTestsToolStripMenuItem_Click(object sender, EventArgs e) private void TransportTestsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormTransportTests)); var service = Program.ServiceProvider?.GetService(typeof(FormTransportTests));
if (service is FormTransportTests form) if (service is FormTransportTests form)
{ {
form.ShowDialog(); form.ShowDialog();
} }
} }
/// <summary> /// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Ìàðøðóò" /// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Ìàðøðóò"
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void RoutesTestsToolStripMenuItem_Click(object sender, EventArgs e) private void RoutesTestsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormRoutesTests)); var service = Program.ServiceProvider?.GetService(typeof(FormRoutesTests));
if (service is FormRoutesTests form) if (service is FormRoutesTests form)
{ {
form.ShowDialog(); form.ShowDialog();
} }
} }
/// <summary> /// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Îñòàíîâêà" /// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Îñòàíîâêà"
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void StopsTestsToolStripMenuItem_Click(object sender, EventArgs e) private void StopsTestsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormStopsTests)); var service = Program.ServiceProvider?.GetService(typeof(FormStopsTests));
if (service is FormStopsTests form) if (service is FormStopsTests form)
{ {
form.ShowDialog(); form.ShowDialog();
} }
} }
/// <summary> /// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Ðàñïèñàíèå" /// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Ðàñïèñàíèå"
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void SchedulesTestsToolStripMenuItem_Click(object sender, EventArgs e) private void SchedulesTestsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormSchedulesTests)); var service = Program.ServiceProvider?.GetService(typeof(FormSchedulesTests));
if (service is FormSchedulesTests form) if (service is FormSchedulesTests form)
{ {
form.ShowDialog(); form.ShowDialog();
} }
} }
/// <summary> /// <summary>
/// Êíîïêà "Ñîçäàòü" /// Êíîïêà "Ñîçäàòü"
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void buttonCreate_Click(object sender, EventArgs e) private void buttonCreate_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormSchedule)); var service = Program.ServiceProvider?.GetService(typeof(FormSchedule));
if (service is FormSchedule form) if (service is FormSchedule form)
{ {
if (form.ShowDialog() == DialogResult.OK) if (form.ShowDialog() == DialogResult.OK)
{ {
LoadData(); LoadData();
} }
} }
} }
/// <summary> /// <summary>
/// Êíîïêà "Èçìåíèòü" /// Êíîïêà "Èçìåíèòü"
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void buttonUpdate_Click(object sender, EventArgs e) private void buttonUpdate_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormSchedule)); var service = Program.ServiceProvider?.GetService(typeof(FormSchedule));
if (service is FormSchedule form) if (service is FormSchedule form)
{ {
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); form.Id = dataGridView.SelectedRows[0].Cells["Id"].Value;
if (form.ShowDialog() == DialogResult.OK) if (form.ShowDialog() == DialogResult.OK)
{ {
LoadData(); LoadData();
} }
} }
} }
} }
/// <summary> /// <summary>
/// Êíîïêà "Óäàëèòü" /// Êíîïêà "Óäàëèòü"
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void buttonDelete_Click(object sender, EventArgs e) private void buttonDelete_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
if (MessageBox.Show("Óäàëèòü çàïèñü?", "Âîïðîñ", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) if (MessageBox.Show("Óäàëèòü çàïèñü?", "Âîïðîñ", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); object id = dataGridView.SelectedRows[0].Cells["Id"].Value;
_logger.LogInformation("Óäàëåíèå ñóùíîñòè 'Ðàñïèñàíèå'"); _logger.LogInformation("Óäàëåíèå ñóùíîñòè 'Ðàñïèñàíèå'");
try try
{ {
if (!_schedulelogic.Delete(new ScheduleBindingModel { Id = id })) if (!_schedulelogic.Delete(new ScheduleBindingModel { Id = id }))
{ {
throw new Exception("Îøèáêà ïðè óäàëåíèè ñóùíîñòè 'Ðàñïèñàíèå'. Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ."); throw new Exception("Îøèáêà ïðè óäàëåíèè ñóùíîñòè 'Ðàñïèñàíèå'. Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ.");
} }
LoadData(); LoadData();
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Îøèáêà óäàëåíèÿ ñóùíîñòè 'Ðàñïèñàíèå'"); _logger.LogError(ex, "Îøèáêà óäàëåíèÿ ñóùíîñòè 'Ðàñïèñàíèå'");
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }
} }
/// <summary> /// <summary>
/// Êíîïêà "Îáíîâèòü" /// Êíîïêà "Îáíîâèòü"
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void buttonRefresh_Click(object sender, EventArgs e) private void buttonRefresh_Click(object sender, EventArgs e)
{ {
LoadData(); LoadData();
} }
/// <summary> /// <summary>
/// Çàãðóçêà äàííûõ /// Êíîïêà "Ñèíõðîíèçèðîâàòü äàííûå"
/// </summary> /// </summary>
private void LoadData() /// <param name="sender"></param>
{ /// <param name="e"></param>
try private void buttonSyncData_Click(object sender, EventArgs e)
{ {
var list = _schedulelogic.ReadList(null); DataTransfer dataTransfer = new DataTransfer();
if (list != null) dataTransfer.SyncData();
{ }
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false; /// <summary>
dataGridView.Columns["RouteId"].Visible = false; /// Çàãðóçêà äàííûõ
dataGridView.Columns["RouteName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; /// </summary>
} private void LoadData()
_logger.LogInformation("Çàãðóçêà ñïèñêà ðàñïèñàíèé"); {
} try
catch (Exception ex) {
{ var list = _schedulelogic.ReadList(null);
_logger.LogError(ex, "Îøèáêà çàãðóçêè ñïèñêà ðàñïèñàíèé"); if (list != null)
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error); {
} dataGridView.DataSource = list;
} dataGridView.Columns["Id"].Visible = false;
} dataGridView.Columns["RouteId"].Visible = false;
dataGridView.Columns["RouteName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Çàãðóçêà ñïèñêà ðàñïèñàíèé");
}
catch (Exception ex)
{
_logger.LogError(ex, "Îøèáêà çàãðóçêè ñïèñêà ðàñïèñàíèé");
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
} }

View File

@ -39,17 +39,17 @@ namespace RouteGuideView
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
private int? _id; private object? _id;
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
public int Id { set { _id = value; } } public object Id { set { _id = value; } }
/// <summary> /// <summary>
/// Список остановок в маршруте /// Список остановок в маршруте
/// </summary> /// </summary>
private Dictionary<int, (IStopModel, int)> _routeStops; private Dictionary<object, (IStopModel<object>, int)> _routeStops;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@ -62,7 +62,7 @@ namespace RouteGuideView
_logger = logger; _logger = logger;
_routeLogic = routeLogic; _routeLogic = routeLogic;
_transportLogic = transportLogic; _transportLogic = transportLogic;
_routeStops = new Dictionary<int, (IStopModel, int)>(); _routeStops = new Dictionary<object, (IStopModel<object>, int)>();
} }
/// <summary> /// <summary>
@ -91,7 +91,7 @@ namespace RouteGuideView
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
if (!_id.HasValue) if (_id == null)
{ {
return; return;
} }
@ -101,13 +101,13 @@ namespace RouteGuideView
_logger.LogInformation("Получение сущности 'Маршрут'"); _logger.LogInformation("Получение сущности 'Маршрут'");
var view = _routeLogic.ReadElement(new RouteSearchModel var view = _routeLogic.ReadElement(new RouteSearchModel
{ {
Id = _id.Value Id = _id
}); });
if (view != null) if (view != null)
{ {
textBoxName.Text = view.Name; textBoxName.Text = view.Name;
comboBoxTransport.SelectedValue = view.TransportId; comboBoxTransport.SelectedValue = view.TransportId;
_routeStops = view.RouteStops ?? new Dictionary<int, (IStopModel, int)>(); _routeStops = view.RouteStops ?? new Dictionary<object, (IStopModel<object>, int)>();
LoadData(); LoadData();
} }
} }
@ -161,7 +161,7 @@ namespace RouteGuideView
var service = Program.ServiceProvider?.GetService(typeof(FormRouteStop)); var service = Program.ServiceProvider?.GetService(typeof(FormRouteStop));
if (service is FormRouteStop form) if (service is FormRouteStop form)
{ {
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); object id = dataGridView.SelectedRows[0].Cells[0].Value;
form.Id = id; form.Id = id;
form.Number = _routeStops[id].Item2; form.Number = _routeStops[id].Item2;
@ -194,7 +194,7 @@ namespace RouteGuideView
try try
{ {
_logger.LogInformation("Удаление остановки.{Id}: {StopName} с позиции в маршруте {Number}", dataGridView.SelectedRows[0].Cells[0].Value, dataGridView.SelectedRows[0].Cells[1].Value, dataGridView.SelectedRows[0].Cells[2].Value); _logger.LogInformation("Удаление остановки.{Id}: {StopName} с позиции в маршруте {Number}", dataGridView.SelectedRows[0].Cells[0].Value, dataGridView.SelectedRows[0].Cells[1].Value, dataGridView.SelectedRows[0].Cells[2].Value);
_routeStops.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value)); _routeStops.Remove(dataGridView.SelectedRows[0].Cells[0].Value);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -241,11 +241,11 @@ namespace RouteGuideView
{ {
Id = _id ?? 0, Id = _id ?? 0,
Name = textBoxName.Text, Name = textBoxName.Text,
TransportId = Convert.ToInt32(comboBoxTransport.SelectedValue), TransportId = comboBoxTransport.SelectedValue,
RouteStops = _routeStops RouteStops = _routeStops
}; };
var operationResult = _id.HasValue ? _routeLogic.Update(model) : _routeLogic.Create(model); var operationResult = _id != null ? _routeLogic.Update(model) : _routeLogic.Create(model);
if (!operationResult) if (!operationResult)
{ {
throw new Exception("Ошибка при сохранении сущности 'Маршрут'. Дополнительная информация в логах."); throw new Exception("Ошибка при сохранении сущности 'Маршрут'. Дополнительная информация в логах.");

View File

@ -26,11 +26,11 @@ namespace RouteGuideView
/// <summary> /// <summary>
/// Идентификатор остановки /// Идентификатор остановки
/// </summary> /// </summary>
public int Id public object Id
{ {
get get
{ {
return Convert.ToInt32(comboBoxStop.SelectedValue); return comboBoxStop.SelectedValue;
} }
set set
{ {
@ -41,7 +41,7 @@ namespace RouteGuideView
/// <summary> /// <summary>
/// Сущность "Остановка" /// Сущность "Остановка"
/// </summary> /// </summary>
public IStopModel? StopModel public IStopModel<object>? StopModel
{ {
get get
{ {

View File

@ -78,7 +78,7 @@ namespace RouteGuideView
var service = Program.ServiceProvider?.GetService(typeof(FormRoute)); var service = Program.ServiceProvider?.GetService(typeof(FormRoute));
if (service is FormRoute form) if (service is FormRoute form)
{ {
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); form.Id = dataGridView.SelectedRows[0].Cells["Id"].Value;
if (form.ShowDialog() == DialogResult.OK) if (form.ShowDialog() == DialogResult.OK)
{ {
LoadData(); LoadData();
@ -98,7 +98,7 @@ namespace RouteGuideView
{ {
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); object id = dataGridView.SelectedRows[0].Cells["Id"].Value;
_logger.LogInformation("Удаление сущности 'Маршрут'"); _logger.LogInformation("Удаление сущности 'Маршрут'");
try try

View File

@ -67,7 +67,7 @@ namespace RouteGuideView
{ {
double time = 0; double time = 0;
var stopwatch = new Stopwatch(); var stopwatch = new Stopwatch();
int transportId = _transportLogic.ReadList(1)![0].Id; object transportId = _transportLogic.ReadList(1)![0].Id;
for (int i = 1; i <= entitiesCount; i++) for (int i = 1; i <= entitiesCount; i++)
{ {
var model = new RouteBindingModel var model = new RouteBindingModel

View File

@ -38,12 +38,12 @@ namespace RouteGuideView
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
private int? _id; private object? _id;
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
public int Id { set { _id = value; } } public object Id { set { _id = value; } }
/// <summary> /// <summary>
/// Констурктор /// Констурктор
@ -85,7 +85,7 @@ namespace RouteGuideView
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
if (!_id.HasValue) if (_id == null)
{ {
return; return;
} }
@ -96,7 +96,7 @@ namespace RouteGuideView
_logger.LogInformation("Получение сущности 'Расписание'"); _logger.LogInformation("Получение сущности 'Расписание'");
var view = _scheduleLogic.ReadElement(new ScheduleSearchModel var view = _scheduleLogic.ReadElement(new ScheduleSearchModel
{ {
Id = _id.Value Id = _id
}); });
if (view != null) if (view != null)
{ {
@ -142,10 +142,10 @@ namespace RouteGuideView
DepartureTime = dateTimePickerDepartureTime.Value, DepartureTime = dateTimePickerDepartureTime.Value,
ArrivalTime = dateTimePickerArrivalTime.Value, ArrivalTime = dateTimePickerArrivalTime.Value,
Frequency = dateTimePickerFrequency.Value, Frequency = dateTimePickerFrequency.Value,
RouteId = Convert.ToInt32(comboBoxRoute.SelectedValue) RouteId = comboBoxRoute.SelectedValue
}; };
var operationResult = _id.HasValue ? _scheduleLogic.Update(model) : _scheduleLogic.Create(model); var operationResult = _id != null ? _scheduleLogic.Update(model) : _scheduleLogic.Create(model);
if (!operationResult) if (!operationResult)
{ {
throw new Exception("Ошибка при сохранении сущности 'Расписание'. Дополнительная информация в логах."); throw new Exception("Ошибка при сохранении сущности 'Расписание'. Дополнительная информация в логах.");

View File

@ -67,7 +67,7 @@ namespace RouteGuideView
{ {
double time = 0; double time = 0;
var stopwatch = new Stopwatch(); var stopwatch = new Stopwatch();
int routeId = _routeLogic.ReadList(1)![0].Id; object routeId = _routeLogic.ReadList(1)![0].Id;
for (int i = 1; i <= entitiesCount; i++) for (int i = 1; i <= entitiesCount; i++)
{ {
var model = new ScheduleBindingModel var model = new ScheduleBindingModel

View File

@ -33,12 +33,12 @@ namespace RouteGuideView
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
private int? _id; private object? _id;
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
public int Id { set { _id = value; } } public object Id { set { _id = value; } }
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@ -57,7 +57,7 @@ namespace RouteGuideView
/// <param name="e"></param> /// <param name="e"></param>
private void FormStop_Load(object sender, EventArgs e) private void FormStop_Load(object sender, EventArgs e)
{ {
if (!_id.HasValue) if (_id == null)
{ {
return; return;
} }
@ -67,7 +67,7 @@ namespace RouteGuideView
_logger.LogInformation("Получение сущности 'Остановка'"); _logger.LogInformation("Получение сущности 'Остановка'");
var view = _stopLogic.ReadElement(new StopSearchModel var view = _stopLogic.ReadElement(new StopSearchModel
{ {
Id = _id.Value Id = _id
}); });
if (view != null) if (view != null)
{ {
@ -117,7 +117,7 @@ namespace RouteGuideView
Number = int.TryParse(textBoxNumber.Text, out int number) ? number : 1 Number = int.TryParse(textBoxNumber.Text, out int number) ? number : 1
}; };
var operationResult = _id.HasValue ? _stopLogic.Update(model) : _stopLogic.Create(model); var operationResult = _id != null ? _stopLogic.Update(model) : _stopLogic.Create(model);
if (!operationResult) if (!operationResult)
{ {
throw new Exception("Ошибка при сохранении сущности 'Остановка'. Дополнительная информация в логах."); throw new Exception("Ошибка при сохранении сущности 'Остановка'. Дополнительная информация в логах.");

View File

@ -78,7 +78,7 @@ namespace RouteGuideView
var service = Program.ServiceProvider?.GetService(typeof(FormStop)); var service = Program.ServiceProvider?.GetService(typeof(FormStop));
if (service is FormStop form) if (service is FormStop form)
{ {
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); form.Id = dataGridView.SelectedRows[0].Cells["Id"].Value;
if (form.ShowDialog() == DialogResult.OK) if (form.ShowDialog() == DialogResult.OK)
{ {
LoadData(); LoadData();
@ -98,7 +98,7 @@ namespace RouteGuideView
{ {
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); object id = dataGridView.SelectedRows[0].Cells["Id"].Value;
_logger.LogInformation("Удаление сущности 'Остановка'"); _logger.LogInformation("Удаление сущности 'Остановка'");
try try

View File

@ -39,12 +39,12 @@ namespace RouteGuideView
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
private int? _id; private object? _id;
/// <summary> /// <summary>
/// Идентификатор /// Идентификатор
/// </summary> /// </summary>
public int Id { set { _id = value; } } public object Id { set { _id = value; } }
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@ -92,7 +92,7 @@ namespace RouteGuideView
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
if (!_id.HasValue) if (_id == null)
{ {
return; return;
} }
@ -103,7 +103,7 @@ namespace RouteGuideView
_logger.LogInformation("Получение сущности 'Транспорт'"); _logger.LogInformation("Получение сущности 'Транспорт'");
var view = _transportLogic.ReadElement(new TransportSearchModel var view = _transportLogic.ReadElement(new TransportSearchModel
{ {
Id = _id.Value Id = _id
}); });
if (view != null) if (view != null)
{ {
@ -157,10 +157,10 @@ namespace RouteGuideView
License = textBoxLicense.Text, License = textBoxLicense.Text,
Type = (TransportType)comboBoxType.SelectedItem, Type = (TransportType)comboBoxType.SelectedItem,
Capacity = int.TryParse(textBoxCapacity.Text, out var capacity) ? capacity : 1, Capacity = int.TryParse(textBoxCapacity.Text, out var capacity) ? capacity : 1,
DriverId = Convert.ToInt32(comboBoxDriver.SelectedValue) DriverId = comboBoxDriver.SelectedValue
}; };
var operationResult = _id.HasValue ? _transportLogic.Update(model) : _transportLogic.Create(model); var operationResult = _id != null ? _transportLogic.Update(model) : _transportLogic.Create(model);
if (!operationResult) if (!operationResult)
{ {
throw new Exception("Ошибка при сохранении сущности 'Транспорт'. Дополнительная информация в логах."); throw new Exception("Ошибка при сохранении сущности 'Транспорт'. Дополнительная информация в логах.");

View File

@ -67,7 +67,7 @@ namespace RouteGuideView
{ {
double time = 0; double time = 0;
var stopwatch = new Stopwatch(); var stopwatch = new Stopwatch();
int driverId = _driverLogic.ReadList(1)![0].Id; object driverId = _driverLogic.ReadList(1)![0].Id;
for (int i = 1; i <= entitiesCount; i++) for (int i = 1; i <= entitiesCount; i++)
{ {
var model = new TransportBindingModel var model = new TransportBindingModel

View File

@ -78,7 +78,7 @@ namespace RouteGuideView
var service = Program.ServiceProvider?.GetService(typeof(FormTransport)); var service = Program.ServiceProvider?.GetService(typeof(FormTransport));
if (service is FormTransport form) if (service is FormTransport form)
{ {
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); form.Id = dataGridView.SelectedRows[0].Cells["Id"].Value;
if (form.ShowDialog() == DialogResult.OK) if (form.ShowDialog() == DialogResult.OK)
{ {
LoadData(); LoadData();
@ -98,7 +98,7 @@ namespace RouteGuideView
{ {
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); object id = dataGridView.SelectedRows[0].Cells["Id"].Value;
_logger.LogInformation("Удаление сущности 'Транспорт'"); _logger.LogInformation("Удаление сущности 'Транспорт'");
try try

View File

@ -4,7 +4,7 @@ using NLog.Extensions.Logging;
using RouteGuideBusinessLogics.BusinessLogics; using RouteGuideBusinessLogics.BusinessLogics;
using RouteGuideContracts.BusinessLogicsContracts; using RouteGuideContracts.BusinessLogicsContracts;
using RouteGuideContracts.StoragesContracts; using RouteGuideContracts.StoragesContracts;
using RouteGuideDatabaseImplement.Implements; using RouteGuideMongoDBImplement.Implements;
namespace RouteGuideView namespace RouteGuideView
{ {

View File

@ -32,6 +32,7 @@
<ProjectReference Include="..\RouteGuideBusinessLogics\RouteGuideBusinessLogics.csproj" /> <ProjectReference Include="..\RouteGuideBusinessLogics\RouteGuideBusinessLogics.csproj" />
<ProjectReference Include="..\RouteGuideContracts\RouteGuideContracts.csproj" /> <ProjectReference Include="..\RouteGuideContracts\RouteGuideContracts.csproj" />
<ProjectReference Include="..\RouteGuideDatabaseImplement\RouteGuideDatabaseImplement.csproj" /> <ProjectReference Include="..\RouteGuideDatabaseImplement\RouteGuideDatabaseImplement.csproj" />
<ProjectReference Include="..\RouteGuideMongoDBImplement\RouteGuideMongoDBImplement.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>