본문 바로가기
ASP.NET Core

ASP.NET Core] Asynchronous Generic Repository

by Fastlane 2023. 4. 26.
728x90
반응형

synchronous repository를 asnychronous repository로 변경해보자. 

 

기존 IRepositoryBase, Repository 소스는 다음과 같다. 

using System.Linq.Expressions;

namespace TEST.Data
{
    public interface IRepoBase<T>
    {
        IQueryable<T> FindAll();
        IQueryable<T> FindByCondition(Expression<Func<T, bool>> expression);
        T GetById(int id);
        void Create(T entity);
        void Update(T entity);
        void Delete(T entity);
    }
}
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace TEST.Data
{
    public abstract class RepoBase<T> : IRepoBase<T> where T : class
    {
        protected AppDbContext _context { get; set; }
        public RepoBase(AppDbContext context)
        {
            _context = context;
        }
        public IQueryable<T> FindAll() => _context.Set<T>().AsNoTracking();
        public IQueryable<T> FindByCondition(Expression<Func<T, bool>> expression) =>
            _context.Set<T>().Where(expression).AsNoTracking();
        public T GetById(int id) => _context.Set<T>().Find(id);
        public void Create(T entity) => _context.Set<T>().Add(entity);
        public void Update(T entity) => _context.Set<T>().Update(entity);
        public void Delete(T entity) => _context.Set<T>().Remove(entity);
    }
}

이중에서 GetById만 비동기로 수정해보자. 

        public T GetById(int id) => _context.Set<T>().Find(id);
        
        public async Task<T> GetByPK(int id) => await _context.Set<T>().FindAsync(id);

IUserRepository와 UserRepository를 수정해보자. 

using TEST.Models;

namespace TEST.Data
{
    public interface IUserRepo : IRepoBase<User>
    {
        bool SaveChanges();
        IEnumerable<User> GetAllUsers();
        User GetUserById(string id);
    }
}
using TEST.Models;

namespace TEST.Data
{
    public interface IUserRepo : IRepoBase<User>
    {
        Task<bool> SaveChanges();
        Task<IEnumerable<User>> GetAllUsers();
        Task<User> GetUserById(string id);
    }
}
using TEST.Models;

namespace TEST.Data
{
    public class UserRepo : RepoBase<User>, IUserRepo
    {
        private readonly AppDbContext _context;

        public UserRepo(AppDbContext context) : base(context)
        {
            _context = context;
        }

        public IEnumerable<User> GetAllUsers()
        {
            return FindAll().ToList();
        }

        public User GetUserById(string id)
        {
            return FindByCondition(owner => owner.EmpId.Equals(id)).FirstOrDefault();
        }

        public bool SaveChanges()
        {
            return (_context.SaveChanges() >= 0);
        }
    }
}
using TEST.Models;
using Microsoft.EntityFrameworkCore;

namespace TEST.Data
{
    public class UserRepo : RepoBase<User>, IUserRepo
    {
        private readonly AppDbContext _context;

        public UserRepo(AppDbContext context) : base(context)
        {
            _context = context;
        }

        public async Task<IEnumerable<User>> GetAllUsers()
        {
            return await FindAll().ToListAsync();
        }

        public async Task<User> GetUserById(string id)
        {
            return await FindByCondition(owner => owner.EmpId.Equals(id)).FirstOrDefaultAsync();
        }

        public async Task<bool> SaveChanges()
        {
            return (await _context.SaveChangesAsync() >= 0);
        }
    }
}

Controller 수정

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using TEST.Data;
using TEST.Models;
using TEST.Services;

namespace SpecEx.Controllers
{
    public class UserController : Controller
    {
        private readonly IUserRepo _repository;
        private readonly IRazorRenderService _renderService;
        public UserController(IUserRepo repository, IRazorRenderService renderService)
        {
            _repository = repository;
            _renderService = renderService;

        }
        public IActionResult Index()
        {
            return View();
        }
        public async Task<PartialViewResult> ViewAllPartial()
        {
            var users = await _repository.GetAllUsers();
            return new PartialViewResult
            {
                ViewName = "_ViewAll",
                ViewData = new ViewDataDictionary<IEnumerable<User>>(ViewData, users)
            };
        }

        [HttpGet]
        public async Task<JsonResult> CreateOrEdit(int id = 0)
        {
            if (id == 0) {
                return new JsonResult(new { isValid = true, html = await _renderService.ToStringAsync("_CreateOrEdit", new User()) });
            }
            else
            {
                var thisUser = await _repository.GetByPK(id);
                return new JsonResult(new { isValid = true, html = await _renderService.ToStringAsync("_CreateOrEdit", thisUser) });
            }
        }

        [HttpPost]
        public async Task<JsonResult> CreateOrEdit(int id, User user)
        {
            if (ModelState.IsValid)
            {
                if (id == 0)
                {
                    user.RegDate = DateTime.Now;
                    user.UpdateDate = DateTime.Now;
                    user.PwdUpdateDate = DateTime.Now;
                    _repository.Create(user);
                    await _repository.SaveChanges();
                }
                else
                {
                    user.EmpIdx = id;
                    user.UpdateDate = DateTime.Now;
                    _repository.Update(user);
                    await _repository.SaveChanges();
                }
                var users = await _repository.GetAllUsers();
                var html = await _renderService.ToStringAsync("_ViewAll", users);
                return new JsonResult(new { isValid = true, html = html });
            }
            else
            {
                var html = await _renderService.ToStringAsync("_CreateOrEdit", user);
                return new JsonResult(new { isValid = false, html = html });
            }
        }

        [HttpPost]
        public async Task<JsonResult> Delete(int id)
        {
            var user = await _repository.GetByPK(id);
            _repository.Delete(user);
            await _repository.SaveChanges();
            var users = await _repository.GetAllUsers();
            var html = await _renderService.ToStringAsync("_ViewAll", users);
            return new JsonResult(new { isValid = true, html = html });
        }
    }
}
728x90
반응형

댓글