AuthorityDs.cs 2.88 KB
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using AutoMapper;
using MapsDb.Interfaces;
using MapsDb.Models;
using MapsModels.DsModels;
using Microsoft.EntityFrameworkCore;

namespace MapsDb.DataService
{
    public class AuthorityDs : IAuthorityDs
    {
        private PostgresDbContext _context;
        public AuthorityDs(){
            _context = new PostgresDbContext();
        }
        public Task<IList<AuthorityEditDsM>> GetIndexListAsync(PaginationDsM pagination){
            return Task.Factory.StartNew(()=> { return GetAllAuthority(pagination); });
        }
        private IList<AuthorityEditDsM> GetAllAuthority(PaginationDsM pagination)
        {

            var filter =  pagination.filter;

            IQueryable<Authority> data = _context.Authority
            .Include(d=>d.Road)
            .Include(d=>d.CrossSection);

            IQueryable<AuthorityEditDsM> result = data
            .Select(Authority => Mapper.Map<AuthorityEditDsM>(Authority))
            .Skip(pagination.from)
            .Take(pagination.perPage);

            switch (pagination.orderType())
            {
                case "ASC":
                    return result.OrderBy(i => i.GetType().GetProperty(pagination.sort).GetValue(i, null)).ToList();
          
                case "DESC":
                    return result.OrderByDescending(i => i.GetType().GetProperty(pagination.sort).GetValue(i, null)).ToList();
            
                default:
                    return result.OrderByDescending(i => i.Id).ToList();
            }     
            
        }

        public Task<Authority> CreateAsync(AuthorityEditDsM data){
              return Task.Factory.StartNew(()=> { return Create(data); });
        }
        private Authority Create(AuthorityEditDsM data)
        {   
            
            Authority Model = InsertModel(data);
            _context.Authority.Add(Model);
            _context.SaveChanges();
            return Model;
        }
        public Task<Authority> UpdateAsync(AuthorityEditDsM data, int id){
            return Task.Factory.StartNew(()=> { return Update(data, id); });
        }
        private Authority Update(AuthorityEditDsM data, int id)
        {   
            Authority Model = InsertModel(data);
            Model.Id = id;
            _context.Authority.Update(Model);
            _context.SaveChanges();
            return Model;
        }
        public Authority InsertModel(AuthorityEditDsM data){
            Authority Model = Mapper.Map<Authority>(data);
            return Model;
        }
        public async Task<int> DeleteAsync(int Id)
        {
            var authority = await _context.Authority.SingleOrDefaultAsync(x => x.Id == Id);
            _context.Authority.Remove(authority);
            return await _context.SaveChangesAsync();
        }
    }
}