Quantcast
Channel: URF - Unit of Work & (extensible/generic) Repositories Framework
Viewing all articles
Browse latest Browse all 1539

Updated Wiki: Adding Custom Queries to Repository

$
0
0
Add extension method for IRepository<TEntity> or (if async) IRepostioryAsync<TEntity>
*Note: all things returned from Repository layer are of type TEntity or IEnumerable<TEntity> and not IQueryable<TEntity> address compartmentalization concern that all queries are actually happening in the Repository layer.

publicstaticclass CustomerRepository
{
    publicstaticdecimal GetCustomerOrderTotalByYear(
        this IRepository<Customer> repository,
        string customerId, int year)
    {
        return repository
            .Find(customerId)
            .Orders.SelectMany(o => o.OrderDetails)
            .Select(o => o.Quantity*o.UnitPrice)
            .Sum();
    }

    // Custom query using IQueryablepublicstatic IEnumerable<Customer> CustomersByCompany(
        this IRepositoryAsync<Customer> repository,
        string companyName)
    {
        return repository
            .Queryable()
            .Where(x => x.CompanyName.Contains(companyName))
            .AsEnumerable();
    }
}

Best practice, expose this through your service layer

publicinterface ICustomerService : IService<Customer>
{
    decimal CustomerOrderTotalByYear(string customerId, int year);
    IEnumerable<Customer> CustomersByCompany(string companyName);
}

publicclass CustomerService : Service<Customer>, ICustomerService
{
    privatereadonly IRepositoryAsync<Customer> _repository;

    public CustomerService(IRepositoryAsync<Customer> repository) : base(repository)
    {
        _repository = repository;
    }

    publicdecimal CustomerOrderTotalByYear(string customerId, int year)
    {
        return _repository.GetCustomerOrderTotalByYear(customerId, year);
    }

    public IEnumerable<Customer> CustomersByCompany(string companyName)
    {
        return _repository.CustomersByCompany(companyName);
    }
}

Example in Web Api

publicclass CustomerController : WebApi
{
    privatereadonly ICustomerService _customerService;

    public CustomerController(ICustomerService customerService)
    {
        _customerService = customerService;
    }

    publicdecimal CustomerOrderTotalByYear(string customerId, int year)
    {
        return _customerService.CustomerOrderTotalByYear(customerId, year);
    }
}


Viewing all articles
Browse latest Browse all 1539

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>