BusStopDs.cs 2.72 KB
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 BusStopDs : IBusStopDs
    {
        private PostgresDbContext _context;
        public BusStopDs(){
            _context = new PostgresDbContext();
            Mapper.Initialize(cnf => {
                cnf.CreateMap<BusStop, BusStopEditDsM>();
                cnf.CreateMap<BusStopEditDsM, BusStop>();
            });            
        }
        public Task<IList<BusStopEditDsM>> GetIndexListAsync(PaginationDsM pagination){
            return Task.Factory.StartNew(()=> { return GetAllBusStop(pagination); });
        }
        private IList<BusStopEditDsM> GetAllBusStop(PaginationDsM pagination)
        {
            var data =  _context.BusStop.Select(BusStop => Mapper.Map<BusStopEditDsM>(BusStop)).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<BusStop> CreateAsync(BusStopEditDsM data){
              return Task.Factory.StartNew(()=> { return Create(data); });
        }
        private BusStop Create(BusStopEditDsM data)
        {   
            
            BusStop Model = InsertModel(data);
            _context.BusStop.Add(Model);
            _context.SaveChanges();
            return Model;
        }
        public Task<BusStop> UpdateAsync(BusStopEditDsM data, int id){
            return Task.Factory.StartNew(()=> { return Update(data, id); });
        }
        private BusStop Update(BusStopEditDsM data, int id)
        {   
            BusStop Model = InsertModel(data);
            Model.Id = id;
            _context.BusStop.Update(Model);
            _context.SaveChanges();
            return Model;
        }
        public BusStop InsertModel(BusStopEditDsM data){
            BusStop Model = Mapper.Map<BusStop>(data);
            return Model;
        }
        public async Task<int> DeleteAsync(int Id)
        {
            var busStop = await _context.BusStop.SingleOrDefaultAsync(x => x.Id == Id);
            _context.BusStop.Remove(busStop);
            return await _context.SaveChangesAsync();
        }
    }
}