Skip to content

Instantly share code, notes, and snippets.

@wi7a1ian
Last active September 12, 2019 10:27
Show Gist options
  • Save wi7a1ian/dd85213c93869b1816695238443f2695 to your computer and use it in GitHub Desktop.
Save wi7a1ian/dd85213c93869b1816695238443f2695 to your computer and use it in GitHub Desktop.
Example of generic repo with basic CRUD that translates persistent entity model to business model in c# #csharp
public class Entity
{
public long Id { get; set; }
}
public class GenericRepository<TB, TD> : IRepository<TB> where TB : Entity, new() where TD : Entity, new()
{
private readonly DbContext _context;
private readonly DbSet<TD> _dbSet;
protected readonly IMapper _mapper;
public GenericRepository(DbContext context, IMapper mapper)
{
_context = context;
_dbSet = context.Set<TD>();
_mapper = mapper;
}
public virtual async Task<IEnumerable<TB>> GetAllAsync()
{
return _mapper.Map<IEnumerable<TB>>(await _dbSet.ToListAsync());
}
public virtual async Task<TB> GetAsync(long id)
{
return _mapper.Map<TB>(await _dbSet.FindAsync(id));
}
public virtual async Task AddAsync(TB item)
{
await _dbSet.AddAsync(_mapper.Map<TD>(item));
await _context.SaveChangesAsync();
}
public virtual async Task UpdateAsync(TB item)
{
var existingItem = await _dbSet.FindAsync(item.Id);
if (existingItem != null)
{
_context.Entry(existingItem).CurrentValues.SetValues(item);
await _context.SaveChangesAsync();
}
}
public virtual async Task DeleteAsync(long id)
{
var item = await _dbSet.FindAsync(id);
if (item != null)
{
_dbSet.Remove(item);
await _context.SaveChangesAsync();
}
}
}
public interface IRepository<TB> where TB : Entity, new()
{
Task<TB> GetAsync(long id);
Task<IEnumerable<TB>> GetAllAsync();
Task AddAsync(TB item);
Task UpdateAsync(TB item);
Task DeleteAsync(long id);
}
public interface ICustomerRepo : IRepository<CustomerEntity>
{
Task<CustomerEntity> GetByLocationAsync(Location loc);
}
public class SqlCustomerRepo : GenericRepository<Core.Models.Customer, Data.Entities.Customer>, ICustomerRepo
{
private readonly NovaDatabaseContext _dbContext;
public SqlCustomerRepo(NovaDatabaseContext context, IMapper mapper) : base(context, mapper)
{
_dbContext = context ?? throw new ArgumentNullException(nameof(context));
}
public async Task<Customer> GetByLocationAsync(Location loc){
var isLocAlreadyExisting = await _dbContext.Locations
.Where(x => x.Id == loc.Id)
.AnyAsync();
if (!isLocAlreadyExisting)
{
throw new ArgumentException($"Location with id {loc.Id} does not exists!");
}
return _mapper.Map<Customer>(await _dbContext.Customer
.Where(x => x.CustomerLocationRef.Any(r => r.LocationId == loc.Id))
.SingleAsync());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment