using Microsoft.EntityFrameworkCore;
using Microsoft.eShopWeb.ApplicationCore.Entities;
using Microsoft.eShopWeb.ApplicationCore.Interfaces;
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 : IAsyncRepository where T : BaseEntity, IAggregateRoot
{
protected readonly CatalogContext _dbContext;
public EfRepository(CatalogContext dbContext)
{
_dbContext = dbContext;
}
public virtual async Task GetByIdAsync(int id)
{
return await _dbContext.Set().FindAsync(id);
}
public async Task> ListAllAsync()
{
return await _dbContext.Set().ToListAsync();
}
public async Task> ListAsync(ISpecification spec)
{
return await ApplySpecification(spec).ToListAsync();
}
public async Task CountAsync(ISpecification spec)
{
return await ApplySpecification(spec).CountAsync();
}
public async Task AddAsync(T entity)
{
await _dbContext.Set().AddAsync(entity);
await _dbContext.SaveChangesAsync();
return entity;
}
public async Task UpdateAsync(T entity)
{
_dbContext.Entry(entity).State = EntityState.Modified;
await _dbContext.SaveChangesAsync();
}
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);
}
}
}