Skip to content

Performing Async Selects with Includes and Sorting

Long Le edited this page Sep 20, 2017 · 2 revisions

Note: The following are typically injected: IRepositoryProvider, IDataContextAsync, IDataContextAsync, IRepository, IRepositoryAsync vs. manually instantiated as they are in the code samples below.

This example queries three levels deep (Customer > Order -> OrderDetails) and sorts on CompanyName then ContactName respectively.

private readonly IRepositoryProvider _repositoryProvider = new RepositoryProvider(new RepositoryFactories());

using (IDataContextAsync context = new NorthwindContext())
using (IUnitOfWorkAsync unitOfWork = new UnitOfWork(context, _repositoryProvider))
{
    IRepositoryAsync<Customer> customerRepository = new Repository<Customer>(context, unitOfWork);
    ICustomerService customerService = new CustomerService(customerRepository);

    var asyncTask = customerService
        .Query(x => x.Country == "USA")
        .Include(x => x
            .Orders
            .Select(y => y.OrderDetails))
        .OrderBy(x => x
            .OrderBy(y => y.CompanyName)
            .ThenBy(z => z.ContactName))
        .SelectAsync();

    var customers = asyncTask.Result;

    Assert.IsTrue(customers.Count() > 1);
    Assert.IsFalse(customers.Count(x => x.Country == "USA") == 0);
}