using Microsoft.eShopWeb.ApplicationCore.Interfaces; using Microsoft.EntityFrameworkCore; using Microsoft.eShopWeb.ApplicationCore.Entities; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Microsoft.eShopWeb.Infrastructure.Data { /// /// "There's some repetition here - couldn't we have some the sync methods call the async?" /// https://blogs.msdn.microsoft.com/pfxteam/2012/04/13/should-i-expose-synchronous-wrappers-for-asynchronous-methods/ /// /// public class EfRepository : IRepository, IAsyncRepository where T : BaseEntity { protected readonly CatalogContext _dbContext; public EfRepository(CatalogContext dbContext) { _dbContext = dbContext; } public T GetSingleBySpec(ISpecification spec) { return List(spec).FirstOrDefault(); } public virtual async Task GetByIdAsync(int id) { return await _dbContext.Set().FindAsync(id); } public async Task> ListAllAsync() { return await _dbContext.Set().ToListAsync(); } public IEnumerable List(ISpecification spec) { return ApplySpecification(spec).AsEnumerable(); } public async Task> ListAsync(ISpecification spec) { return await ApplySpecification(spec).ToListAsync(); } public int Count(ISpecification spec) { return ApplySpecification(spec).Count(); } public async Task CountAsync(ISpecification spec) { return await ApplySpecification(spec).CountAsync(); } public async Task AddAsync(T entity) { _dbContext.Set().Add(entity); await _dbContext.SaveChangesAsync(); return entity; } public void Update(T entity) { _dbContext.Entry(entity).State = EntityState.Modified; _dbContext.SaveChanges(); } public async Task UpdateAsync(T entity) { _dbContext.Entry(entity).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); } public void Delete(T entity) { _dbContext.Set().Remove(entity); _dbContext.SaveChanges(); } public async Task DeleteAsync(T entity) { _dbContext.Set().Remove(entity); await _dbContext.SaveChangesAsync(); } private IQueryable ApplySpecification(ISpecification spec) { return SpecificationEvaluator.GetQuery(_dbContext.Set().AsQueryable(), spec); } } }