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>, addressing compartmentalization concern that all queries are actually happening in the Repository layer.
Best practice, expose this through your service layer
Example in Web Api
*Note: all things returned from Repository layer are of type TEntity or IEnumerable<TEntity> and not IQueryable<TEntity>, addressing 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; } public HttpResponseMessage CustomerOrderTotalByYear(string customerId, int year) { return Request.CreateResponse(HttpStatus.Ok, _customerService.CustomerOrderTotalByYear(customerId, year)); } }