Skip to content
Hamed ZVand edited this page Oct 26, 2019 · 2 revisions

SmartRepository

Lightweight implementation of Repository pattern with the help of auto-mapper


Installation (based on Entity Framework provider)

You should install Alamut.Data.EF with NuGet:

Install-Package Alamut.Data.EF

Or via the .NET Core command-line interface:

dotnet add package Alamut.Data.EF 

Setup

in Startup file register the generic repository:

services.AddScoped(typeof(Alamut.Data.Repository.ISmartRepository<>), typeof(Alamut.Data.EF.SmartRepository<>));

Methods:

  • Task<TDto> Get<TDto>(Expression<Func<TEntity, bool>> predicate)
    gets an item (mapped to provided TDto) filter by provided predicate
BlogDto result = await _blogRepository.Get<BlogDto>(q => q.Id == id);
  • Task<List<TDto>> GetAll<TDto>()
    gets all items (mapped to provided TDto)
List<BlogDto> result = await _blogRepository.GetAll<BlogDto>();
  • Task<List<TDto>> GetMany<TDto>(Expression<Func<TEntity, bool>> predicate)
    gets a list of items (mapped to provided TDto) filter by provided predicate
List<BlogDto> dtos = await repository.GetMany<BlogDto>(q => q.Rating > 4);
  • Task<IPaginated<TDto>> GetPaginated<TDto>(IPaginatedCriteria criteria = null)
    gets a list of requested DTO in Paginated data-type filtered by provided criteria or default
IPaginated<BlogDto> actual = await repository.GetPaginated<BlogDto>(new PaginatedCriteria(2, 10));
  • TEntity Add<TDto>(TDto dto);
    maps the provided DTO to the Entity and add it to the current context
[HttpPost]
public async Task<ActionResult<Result>> Post([FromBody] BlogDto value)
{
    _blogRepository.Add(value);
    
    var result = await _blogRepository.CommitAsync(CancellationToken.None);

    return result ? Ok(result) : StatusCode(result.StatusCode, result);
}
  • Task<TEntity> UpdateById<TDto>(object id,TDto dto)
    maps the provided DTO to the Entity and update it to the current context
[HttpPut("{id}")]
public async Task<ActionResult<Result>> Put(int id, [FromBody] BlogDto value)
{
    await _blogRepository.UpdateById(id, value);

    var result = await _blogRepository.CommitAsync(CancellationToken.None);

    return result ? Ok(result) : StatusCode(result.StatusCode, result);
}
Clone this wiki locally