Quick Samples in LINQPad
*Please download to see real world implementation in sample ASP.NET MVC 5 application.

Download to LINQPad *linq file used in this example: https://onedrive.live.com/redir?resid=949A1C97C2A17906%217197

Simple query for all categories
*Initializing of UnitofWork and Repositories would be facilitated by DI & IoC in real world implementation.


// Initialize a repository (obviously this would be injected in real world implementation)
var categoryRepository = new Repository<Category>(this);

var categories1 = categoryRepository
	.Query()
	.Select();

categories1.Dump();


Simple query, with clause and sorting


var categories2 = categoryRepository
	.Query(c => c.CategoryID < 5)
	.OrderBy(x => x.OrderBy(y => y.CategoryName)
		.ThenBy(w => w.CategoryID))
	.Select();
	
categories2.Dump();


Simple query with deep loading graph and projection


var categories = categoryRepository
	.Query(x => x.CategoryName == "Produce")
		.Include(x => x.Products.Select(p => p.Supplier))
		.Include(x => x.Products.Select(p => p.OrderDetails))
	.Select(x => new {
			CategoryId = x.CategoryID,
			ProductCount = x.Products.Count(),
			ItemsSold = x.Products.SelectMany(p => p.OrderDetails).Sum(p => p.Quantity)
		});
	
categories.Dump();


Accessing repositories from UnitOfWork, with async (EF6 only)
(obviously this would be injected in real world implementation)


IUnitOfWorkAsync unitOfWork = new UnitOfWork(this);	
var product1 = await unitOfWork.RepositoryAsync<Product>().FindAsync(2);
product1.Dump();


Async hybrid deletes


var isDeleted = await productRepository.DeleteAsync(2);


If everything from the Repository returns a single Entity or IEnumerable, how do I support OData which needs IQueryable? Framework, supports OData!


public class CustomerController : ODataController
{
    private readonly IRepositoryAsync<Customer> _customerRepository;

    public CustomerController(IRepositoryAsync<Customer> customerRepository)
    {
        _customerRepository = customerRepository;
    }

    // GET odata/Customer
    public PageResult<Customer> GetCustomer(ODataQueryOptions<Customer> oDataQueryOptions)
    {
        var queryable = _customerRepository.ODataQueryable(oDataQueryOptions);

        return new PageResult<Customer>(
            queryable as IEnumerable<Customer>, 
            Request.GetNextPageLink(),
            Request.GetInlineCount());
    }
}

Last edited Sep 23, 2014 at 7:21 PM by lelong37, version 8