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
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RouteGuideDatabaseImplement", "RouteGuideDatabaseImplement\RouteGuideDatabaseImplement.csproj", "{5C2BBCAA-01A8-4B4C-B296-E7CF8DFBA884}"
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
Global
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}.Release|Any CPU.ActiveCfg = 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
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

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

View File

@ -204,7 +204,7 @@ namespace RouteGuideBusinessLogics.BusinessLogics
{
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));
}
@ -215,7 +215,7 @@ namespace RouteGuideBusinessLogics.BusinessLogics
{
Name = model.Name
});
if (element != null && element.Id != model.Id)
if (element != null && !element.Id.Equals(model.Id))
{
throw new InvalidOperationException("Маршрут с таким названием уже существует");
}

View File

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

View File

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

View File

@ -208,7 +208,7 @@ namespace RouteGuideBusinessLogics.BusinessLogics
{
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));
}
@ -219,7 +219,7 @@ namespace RouteGuideBusinessLogics.BusinessLogics
{
License = model.License
});
if (element != null && element.Id != model.Id)
if (element != null && !element.Id.Equals(model.Id))
{
throw new InvalidOperationException("Транспортное средство с таким номерным знаком уже есть");
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -15,7 +15,7 @@ namespace RouteGuideDatabaseImplement.Models
/// <summary>
/// Сущность "Маршрут"
/// </summary>
public class Route : IRouteModel
public class Route : IRouteModel<int>
{
/// <summary>
/// Идентификатор
@ -42,20 +42,20 @@ namespace RouteGuideDatabaseImplement.Models
/// <summary>
/// Коллекция остановок маршрута
/// </summary>
private Dictionary<int, (IStopModel, int)>? _routeStops = null;
private Dictionary<int, (IStopModel<int>, int)>? _routeStops = null;
/// <summary>
/// Коллекция остановок маршрута
/// </summary>
[NotMapped]
public Dictionary<int, (IStopModel, int)> RouteStops
public Dictionary<int, (IStopModel<int>, int)> RouteStops
{
get
{
if (_routeStops == null)
{
_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;
}
@ -77,14 +77,14 @@ namespace RouteGuideDatabaseImplement.Models
{
return new Route()
{
Id = model.Id,
Id = (int)model.Id,
Name = model.Name,
TransportId = model.TransportId,
TransportId = (int)model.TransportId,
Transport = context.Transport
.FirstOrDefault(x => x.Id == model.TransportId),
.FirstOrDefault(x => x.Id.Equals(model.TransportId)),
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
}).ToList()
};
@ -112,7 +112,14 @@ namespace RouteGuideDatabaseImplement.Models
Id = Id,
Name = Name,
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
};
@ -123,7 +130,7 @@ namespace RouteGuideDatabaseImplement.Models
/// <param name="model"></param>
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)
{
// Удаление остановок, которых нет в маршруте
@ -144,7 +151,7 @@ namespace RouteGuideDatabaseImplement.Models
context.RouteStops.Add(new RouteStop
{
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
});
context.SaveChanges();

View File

@ -15,7 +15,7 @@ namespace RouteGuideDatabaseImplement.Models
/// <summary>
/// Сущность "Расписание"
/// </summary>
public class Schedule : IScheduleModel
public class Schedule : IScheduleModel<int>
{
/// <summary>
/// Идентификатор
@ -71,14 +71,14 @@ namespace RouteGuideDatabaseImplement.Models
return new Schedule()
{
Id = model.Id,
Id = (int)model.Id,
Date = model.Date,
DepartureTime = model.DepartureTime,
ArrivalTime = model.ArrivalTime,
Frequency = model.Frequency,
RouteId = model.RouteId,
RouteId = (int)model.RouteId,
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>
public class Stop : IStopModel
public class Stop : IStopModel<int>
{
/// <summary>
/// Идентификатор
@ -53,7 +53,7 @@ namespace RouteGuideDatabaseImplement.Models
return new Stop()
{
Id = model.Id,
Id = (int)model.Id,
Name = model.Name,
Street = model.Street,
Number = model.Number
@ -74,7 +74,7 @@ namespace RouteGuideDatabaseImplement.Models
return new Stop()
{
Id = model.Id,
Id = (int)model.Id,
Name = model.Name,
Street = model.Street,
Number = model.Number

View File

@ -16,7 +16,7 @@ namespace RouteGuideDatabaseImplement.Models
/// <summary>
/// Сущность "Транспорт"
/// </summary>
public class Transport : ITransportModel
public class Transport : ITransportModel<int>
{
/// <summary>
/// Идентификатор
@ -66,13 +66,13 @@ namespace RouteGuideDatabaseImplement.Models
return new Transport()
{
Id = model.Id,
Id = (int)model.Id,
License = model.License,
Type = model.Type,
Capacity = model.Capacity,
DriverId = model.DriverId,
DriverId = (int)model.DriverId,
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>
private int? _id;
private object? _id;
/// <summary>
/// Идентификатор
/// </summary>
public int Id { set { _id = value; } }
public object Id { set { _id = value; } }
/// <summary>
/// Конструктор
@ -55,7 +55,7 @@ namespace RouteGuideView
/// <param name="e"></param>
private void FormDriver_Load(object sender, EventArgs e)
{
if (!_id.HasValue)
if (_id == null)
{
return;
}
@ -65,7 +65,7 @@ namespace RouteGuideView
_logger.LogInformation("Получение сущности 'Водитель'");
var view = _driverLogic.ReadElement(new DriverSearchModel
{
Id = _id.Value
Id = _id
});
if (view != null)
{
@ -104,13 +104,13 @@ namespace RouteGuideView
{
var model = new DriverBindingModel
{
Id = _id ?? 0,
Id = _id,
FullName = textBoxFullName.Text,
Phone = textBoxPhone.Text,
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)
{
throw new Exception("Ошибка при сохранении сущности 'Водитель'. Дополнительная информация в логах.");

View File

@ -75,7 +75,7 @@ namespace RouteGuideView
var service = Program.ServiceProvider?.GetService(typeof(FormDriver));
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)
{
LoadData();
@ -95,7 +95,7 @@ namespace RouteGuideView
{
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("Удаление сущности 'Водитель'");
try

View File

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

View File

@ -2,273 +2,285 @@ using Microsoft.Extensions.Logging;
using RouteGuideBusinessLogics.BusinessLogics;
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.BusinessLogicsContracts;
using RouteGuideMongoDBImplement;
namespace RouteGuideView
{
/// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà ðàñïèñàíèé
/// </summary>
public partial class FormMain : Form
{
/// <summary>
/// Ëîããåð
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà ðàñïèñàíèé
/// </summary>
public partial class FormMain : Form
{
/// <summary>
/// Ëîããåð
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Áèçíåñ-ëîãèêà äëÿ ðàñïèñàíèé
/// </summary>
private readonly IScheduleLogic _schedulelogic;
/// <summary>
/// Áèçíåñ-ëîãèêà äëÿ ðàñïèñàíèé
/// </summary>
private readonly IScheduleLogic _schedulelogic;
/// <summary>
/// Êîíñòðóêòîð
/// </summary>
/// <param name="logger"></param>
/// <param name="scheduleLogic"></param>
public FormMain(ILogger<FormMain> logger, IScheduleLogic scheduleLogic)
{
InitializeComponent();
_logger = logger;
_schedulelogic = scheduleLogic;
}
/// <summary>
/// Êîíñòðóêòîð
/// </summary>
/// <param name="logger"></param>
/// <param name="scheduleLogic"></param>
public FormMain(ILogger<FormMain> logger, IScheduleLogic scheduleLogic)
{
InitializeComponent();
_logger = logger;
_schedulelogic = scheduleLogic;
}
/// <summary>
/// Çàãðóçêà äàííûõ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
/// <summary>
/// Çàãðóçêà äàííûõ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
/// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà âîäèòåëåé
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DrviversToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormDrivers));
if (service is FormDrivers form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà âîäèòåëåé
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DrviversToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormDrivers));
if (service is FormDrivers form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà òðàíñïîðòà
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TransportToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormTransports));
if (service is FormTransports form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà òðàíñïîðòà
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TransportToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormTransports));
if (service is FormTransports form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà ìàðøðóòîâ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RoutesToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormRoutes));
if (service is FormRoutes form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà ìàðøðóòîâ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RoutesToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormRoutes));
if (service is FormRoutes form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà îñòàíîâîê
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void StopsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormStops));
if (service is FormStops form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà îñòàíîâîê
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void StopsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormStops));
if (service is FormStops form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Âîäèòåëü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DriversTestsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormDriversTests));
if (service is FormDriversTests form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Âîäèòåëü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DriversTestsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormDriversTests));
if (service is FormDriversTests form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Òðàíñïîðò"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TransportTestsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormTransportTests));
if (service is FormTransportTests form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Òðàíñïîðò"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TransportTestsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormTransportTests));
if (service is FormTransportTests form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Ìàðøðóò"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RoutesTestsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormRoutesTests));
if (service is FormRoutesTests form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Ìàðøðóò"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RoutesTestsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormRoutesTests));
if (service is FormRoutesTests form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Îñòàíîâêà"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void StopsTestsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormStopsTests));
if (service is FormStopsTests form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Îñòàíîâêà"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void StopsTestsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormStopsTests));
if (service is FormStopsTests form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Ðàñïèñàíèå"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SchedulesTestsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSchedulesTests));
if (service is FormSchedulesTests form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Ðàñïèñàíèå"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SchedulesTestsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSchedulesTests));
if (service is FormSchedulesTests form)
{
form.ShowDialog();
}
}
/// <summary>
/// Êíîïêà "Ñîçäàòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreate_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSchedule));
if (service is FormSchedule form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
/// <summary>
/// Êíîïêà "Ñîçäàòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreate_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSchedule));
if (service is FormSchedule form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
/// <summary>
/// Êíîïêà "Èçìåíèòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonUpdate_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSchedule));
if (service is FormSchedule form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
/// <summary>
/// Êíîïêà "Èçìåíèòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonUpdate_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSchedule));
if (service is FormSchedule form)
{
form.Id = dataGridView.SelectedRows[0].Cells["Id"].Value;
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
/// <summary>
/// Êíîïêà "Óäàëèòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonDelete_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Óäàëèòü çàïèñü?", "Âîïðîñ", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Óäàëåíèå ñóùíîñòè 'Ðàñïèñàíèå'");
/// <summary>
/// Êíîïêà "Óäàëèòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonDelete_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Óäàëèòü çàïèñü?", "Âîïðîñ", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
object id = dataGridView.SelectedRows[0].Cells["Id"].Value;
_logger.LogInformation("Óäàëåíèå ñóùíîñòè 'Ðàñïèñàíèå'");
try
{
if (!_schedulelogic.Delete(new ScheduleBindingModel { Id = id }))
{
throw new Exception("Îøèáêà ïðè óäàëåíèè ñóùíîñòè 'Ðàñïèñàíèå'. Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Îøèáêà óäàëåíèÿ ñóùíîñòè 'Ðàñïèñàíèå'");
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
try
{
if (!_schedulelogic.Delete(new ScheduleBindingModel { Id = id }))
{
throw new Exception("Îøèáêà ïðè óäàëåíèè ñóùíîñòè 'Ðàñïèñàíèå'. Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Îøèáêà óäàëåíèÿ ñóùíîñòè 'Ðàñïèñàíèå'");
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
/// <summary>
/// Êíîïêà "Îáíîâèòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRefresh_Click(object sender, EventArgs e)
{
LoadData();
}
/// <summary>
/// Êíîïêà "Îáíîâèòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRefresh_Click(object sender, EventArgs e)
{
LoadData();
}
/// <summary>
/// Çàãðóçêà äàííûõ
/// </summary>
private void LoadData()
{
try
{
var list = _schedulelogic.ReadList(null);
if (list != null)
{
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);
}
}
}
/// <summary>
/// Êíîïêà "Ñèíõðîíèçèðîâàòü äàííûå"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSyncData_Click(object sender, EventArgs e)
{
DataTransfer dataTransfer = new DataTransfer();
dataTransfer.SyncData();
}
/// <summary>
/// Çàãðóçêà äàííûõ
/// </summary>
private void LoadData()
{
try
{
var list = _schedulelogic.ReadList(null);
if (list != null)
{
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>
private int? _id;
private object? _id;
/// <summary>
/// Идентификатор
/// </summary>
public int Id { set { _id = value; } }
public object Id { set { _id = value; } }
/// <summary>
/// Список остановок в маршруте
/// </summary>
private Dictionary<int, (IStopModel, int)> _routeStops;
private Dictionary<object, (IStopModel<object>, int)> _routeStops;
/// <summary>
/// Конструктор
@ -62,7 +62,7 @@ namespace RouteGuideView
_logger = logger;
_routeLogic = routeLogic;
_transportLogic = transportLogic;
_routeStops = new Dictionary<int, (IStopModel, int)>();
_routeStops = new Dictionary<object, (IStopModel<object>, int)>();
}
/// <summary>
@ -91,7 +91,7 @@ namespace RouteGuideView
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (!_id.HasValue)
if (_id == null)
{
return;
}
@ -101,13 +101,13 @@ namespace RouteGuideView
_logger.LogInformation("Получение сущности 'Маршрут'");
var view = _routeLogic.ReadElement(new RouteSearchModel
{
Id = _id.Value
Id = _id
});
if (view != null)
{
textBoxName.Text = view.Name;
comboBoxTransport.SelectedValue = view.TransportId;
_routeStops = view.RouteStops ?? new Dictionary<int, (IStopModel, int)>();
_routeStops = view.RouteStops ?? new Dictionary<object, (IStopModel<object>, int)>();
LoadData();
}
}
@ -161,7 +161,7 @@ namespace RouteGuideView
var service = Program.ServiceProvider?.GetService(typeof(FormRouteStop));
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.Number = _routeStops[id].Item2;
@ -194,7 +194,7 @@ namespace RouteGuideView
try
{
_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)
{
@ -241,11 +241,11 @@ namespace RouteGuideView
{
Id = _id ?? 0,
Name = textBoxName.Text,
TransportId = Convert.ToInt32(comboBoxTransport.SelectedValue),
TransportId = comboBoxTransport.SelectedValue,
RouteStops = _routeStops
};
var operationResult = _id.HasValue ? _routeLogic.Update(model) : _routeLogic.Create(model);
var operationResult = _id != null ? _routeLogic.Update(model) : _routeLogic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении сущности 'Маршрут'. Дополнительная информация в логах.");

View File

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

View File

@ -78,7 +78,7 @@ namespace RouteGuideView
var service = Program.ServiceProvider?.GetService(typeof(FormRoute));
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)
{
LoadData();
@ -98,7 +98,7 @@ namespace RouteGuideView
{
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("Удаление сущности 'Маршрут'");
try

View File

@ -67,7 +67,7 @@ namespace RouteGuideView
{
double time = 0;
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++)
{
var model = new RouteBindingModel

View File

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

View File

@ -67,7 +67,7 @@ namespace RouteGuideView
{
double time = 0;
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++)
{
var model = new ScheduleBindingModel

View File

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

View File

@ -78,7 +78,7 @@ namespace RouteGuideView
var service = Program.ServiceProvider?.GetService(typeof(FormStop));
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)
{
LoadData();
@ -98,7 +98,7 @@ namespace RouteGuideView
{
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("Удаление сущности 'Остановка'");
try

View File

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

View File

@ -67,7 +67,7 @@ namespace RouteGuideView
{
double time = 0;
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++)
{
var model = new TransportBindingModel

View File

@ -78,7 +78,7 @@ namespace RouteGuideView
var service = Program.ServiceProvider?.GetService(typeof(FormTransport));
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)
{
LoadData();
@ -98,7 +98,7 @@ namespace RouteGuideView
{
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("Удаление сущности 'Транспорт'");
try

View File

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

View File

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