using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using AutoMapper; using MapsDb.Interfaces; using MapsDb.Models; using MapsModels.DsModels; using Microsoft.EntityFrameworkCore; namespace MapsDb.DataService { public class RoadServiceDs : IRoadServiceDs { private PostgresDbContext _context; public RoadServiceDs(){ _context = new PostgresDbContext(); } public Task> GetIndexListAsync(PaginationDsM pagination){ return Task.Factory.StartNew(()=> { return GetAllRoadService(pagination); }); } private IList GetAllRoadService(PaginationDsM pagination) { var data = _context.RoadService.Select(RoadService => Mapper.Map(RoadService)).Skip(pagination.from).Take(pagination.perPage); switch (pagination.orderType()) { case "ASC": return data.OrderBy(i => i.GetType().GetProperty(pagination.sort).GetValue(i, null)).ToList(); case "DESC": return data.OrderByDescending(i => i.GetType().GetProperty(pagination.sort).GetValue(i, null)).ToList(); default: return data.OrderByDescending(i => i.Id).ToList(); } } public Task CreateAsync(RoadServiceEditDsM data){ return Task.Factory.StartNew(()=> { return Create(data); }); } private RoadService Create(RoadServiceEditDsM data) { RoadService Model = InsertModel(data); _context.RoadService.Add(Model); _context.SaveChanges(); return Model; } public Task UpdateAsync(RoadServiceEditDsM data, int id){ return Task.Factory.StartNew(()=> { return Update(data, id); }); } private RoadService Update(RoadServiceEditDsM data, int id) { RoadService Model = InsertModel(data); Model.Id = id; _context.RoadService.Update(Model); _context.SaveChanges(); return Model; } public RoadService InsertModel(RoadServiceEditDsM data){ RoadService Model = Mapper.Map(data); return Model; } public async Task DeleteAsync(int Id) { var roadService = await _context.RoadService.SingleOrDefaultAsync(x => x.Id == Id); _context.RoadService.Remove(roadService); return await _context.SaveChangesAsync(); } } }