Skip to content

Parte 12

WILSON DE OLIVEIRA JUNIOR edited this page Mar 9, 2020 · 5 revisions

[Voltar]

Padrão "Repository", criando repositório especializado para a classe Category.

  1. Crie uma nova classe dentro do projeto Taste.Domain na pasta Interfaces chamada ICategoryRepository.cs.
  2. O código de ICategoryRepository.cs deve ser o seguinte:
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
using System.Threading.Tasks;
using Taste.Domain.Entities;

namespace Taste.Domain.Interfaces
{
    public interface ICategoryRepository : IRepository<Category>
    {
        Task<IEnumerable<SelectListItem>> GetCategoryListForDropDown();

        Task Update(Category entity);
    }
}
  1. Agora, dentro do projeto Taste.DataAccess dentro da pasta Repository crie a classe CategoryRepository.cs.
  2. Abaixo, o código da classe CategoryRepository.cs:
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Taste.Domain.Entities;
using Taste.Domain.Interfaces;

namespace Taste.DataAccess.Repository
{
    public class CategoryRepository : BaseRepository<Category>, ICategoryRepository
    {
        private readonly ApplicationDbContext _db;

        public CategoryRepository(ApplicationDbContext db) : base(db)
        {
            _db = db;
        }

        public async Task<IEnumerable<SelectListItem>> GetCategoryListForDropDown()
        {
            return await _db.Categories.Select(i => new SelectListItem()
            {
                Text = i.Name,
                Value = i.Id.ToString()
            }).ToListAsync();
        }

        public async Task Update(Category entity)
        {
            var model = await _db.Categories.FirstOrDefaultAsync(x => x.Id == entity.Id);

            model.Name = entity.Name;
            model.Order = entity.Order;

            await _db.SaveChangesAsync();
        }
    }
}

[Voltar]

Clone this wiki locally