Unit of Work & Repository Framework with ASP.NET MVC 5, Entity Framework 6 & Unity 3 (Quick-Start Video)

Update: 08/12/2014 – Please refer to https://genericunitofworkandrepositories.codeplex.com/documentation for latest documentation. There have been breaking changes released since this recording was published.

Update: 02/24/2014 – v3.2 released, improved API and reusable queries with the Object Query Pattern. Breaking change: Framework now ships returning all things TEntity or IEnumberable for compartmentalization, you will need to change the Repository.cs (see below, what methods signatures to change) if IQueryable is preferred over IEnumerable, IEnumerable is preferred as a best practice (http://genericunitofworkandrepositories.codeplex.com/documentation).

Update: 01/06/2014 – When viewing please configure your YouTube
player to 1080p for clear viewing of the coded demos.

https://genericunitofworkandrepositories.codeplex.com/documentation

Hope everyone had a wonderful New Years holiday, with the new year starting wanted to fulfill a high request, which was a quick start video on the Unit of Work and Repository Frameworks in ASP.NET MVC with Unity for IoC and DI.

This video will touch on the following topics:

  • Entity Framework Power Tools
  • Uow & Repo Framework
  • Generating EF Mappings and POCO’s
  • Upgrading the stack to EF 6.2
  • Basic Customer CRUD Use Case with MVC Scafolding Template w/ Async
  • Refactoring the CustomerController to use UoW & Repo Framework w/ Async
  • Why the ICustomerService Approach?
  • Why Commit Unit of Work Outside the Service vs. versa
  • Quick Examples with Eager Loading, Filter, and Sorting

Sample application download: https://skydrive.live.com/redir?resid=949A1C97C2A17906%216769
(Please enable Nuget Packages Restore at the Solution Level)

Questions and/or comments please tweet @LeLong37.

Note:

1. Although the quick start video, takes the approach of committing the unit of work outside the ICustomerService exampled, whether you choose to do this inside your services or manage this outside, there is no right or wrong, this is totally team preference.

2. Also all use cases demonstrated in the CustomerController could have been satisfied by using the UnitOfWork out of the box without the need to implement the ICustomerService, however as mentioned, this is the preferred best practice.

Using ICustomerService in CustomerController


[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "CustomerID,CompanyName,ContactName,ContactTitle,Address,City,Region,PostalCode,Country,Phone,Fax")] Customer customer)
{
    if (ModelState.IsValid)
    {
        customer.ObjectState = ObjectState.Modified;
        _customerService.Update(customer);
        await _unitOfWork.SaveAsync();
        return RedirectToAction("Index");
    }
    return View(customer);
}

Without ICustomerService and using IUnitOfWork out of the box in the CustomerController


[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "CustomerID,CompanyName,ContactName,ContactTitle,Address,City,Region,PostalCode,Country,Phone,Fax")] Customer customer)
{
    if (ModelState.IsValid)
    {
        customer.ObjectState = ObjectState.Modified;
        _unitOfWork.Repository<Customer>().Update(customer);
        await _unitOfWork.SaveAsync();
        return RedirectToAction("Index");
    }
    return View(customer);
}

In this case it is preferred that the IRepository return IEnumerable vs. IQueryable.

HAVING THE REPOSITORY RETURN ALL THINGS IEnumerable or IList is a best practice and preferred approach. Down the line, if you were to ever switch out your back-end, you won’t be bound to the requirements that the back-end implements IQueryable e.g. moving from EF to pure REST services.

Question? Why does the Repository in the framework return IQueryable?

Answer: Because most devs have been spoiled with ORM’s (e.g. nHibernate.Linq, Linq to Sql, Entity Framework) returning IQueryable and I received to many requests and complaints when the Repository layer in the Framework was returning IEnumerable or IList. Another caveat is that you can’t definitively tell what SQL queries are happening in your application by looking at the Repository layer, because you haven’t truly compartmentalized them in this layer; developers are more than able to modify the query plan before the query is actually executed.

For teams that prefer all things returned as IEnumerable from Repository layer, this would require three lines of code to be changed in the framework, here’s how:

  1. Repository.IRepositoryQuery.cs

    
    IEnumerable<TEntity> Get();
    
    
  2. Repository.RepositoryQuery.cs

    
            public IEnumerable<TEntity> Get()
            {
                return _repository.Get(_filter, _orderByQuerable, _includeProperties, _page, _pageSize);
            }
    
    
  3. Repository.Repository.cs

    
            internal IEnumerable<TEntity> Get(
                Expression<Func<TEntity, bool>> filter = null,
                Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
                List<Expression<Func<TEntity, object>>> includeProperties = null,
                int? page = null,
                int? pageSize = null)
            {
                IQueryable<TEntity> query = _dbSet;
    
                if (includeProperties != null)
                    includeProperties.ForEach(i => query = query.Include(i));
    
                if (filter != null)
                    query = query.Where(filter);
    
                if (orderBy != null)
                    query = orderBy(query);
    
                if (page != null && pageSize != null)
                    query = query
                        .Skip((page.Value - 1) * pageSize.Value)
                        .Take(pageSize.Value);
    
                return query;
            }
    
    
    

Additional references: http://blog.longle.net/2013/05/11/genericizing-the-unit-of-work-pattern-repository-pattern-with-entity-framework-in-mvc/

Sample application download: https://skydrive.live.com/redir?resid=949A1C97C2A17906%216769

CodePlex download for the framework: https://genericunitofworkandrepositories.codeplex.com/

Happy coding…! 🙂

Upgrading to Async with Entity Framework, Web Api, OData AsyncEntitySetController, Kendo UI, Glimpse & Generic Unit of Work Repository Framework v2.0

Update [11/18/2013]: Added mocked DbContext and DbSet and example Unit Tests using the mocks, download v2.1 https://genericunitofworkandrepositories.codeplex.com.

Thanks to everyone for allowing us to give back to the .NET community, we released Generic Unit of Work and Repository Framework v1.0 for four weeks and received 655 downloads and 4121 views. This post will also serve as the documentation for release v2.0. Thanks to Ivan (@ifarkas) for helping out on the Async development, Ken for debugging the Unit of Work life cycle management for use in web applications with DI & IoC (specifically with Entlib Unity v3.0) and scaling the framework to handle Bounded DbContexts, and to the Glimpse Team (@nickswan ) for helping out on getting Glimpse MVC4 working with MVC5, and providing guidance on how to leverage Glimpse EF6 to view SQL queries from EF.

This will be part six of a six part series of blog posts.

  1. Modern Web Application Layered High Level Architecture with SPA, MVC, Web API, EF, Kendo UI, OData
  2. Generically Implementing the Unit of Work & Repository Pattern with Entity Framework in MVC & Simplifying Entity Graphs
  3. MVC 4, Kendo UI, SPA with Layout, View, Router & MVVM
  4. MVC 4, Web API, OData, EF, Kendo UI, Grid, Datasource (CRUD) with MVVM
  5. MVC 4, Web API, OData, EF, Kendo UI, Binding a Form to Datasource (CRUD) with MVVM
  6. Upgrading to Async with Entity Framework, MVC, OData AsyncEntitySetController, Kendo UI, Glimpse & Generic Unit of Work Repository Framework v2.0

We’ll continue on from the most recent post in this series, you can do a quick review of it here http://blog.longle.net/2013/06/19/mvc-4-web-api-odata-ef-kendo-ui-binding-a-form-to-datasource-crud-with-mvvm-part. Now let’s get right into it, by first taking a look at what was all involved on the server side.

First off let’s take a quick look and the changes we made to our DbContextBase to support Async.

Repository.DbContextBase.cs

Before


    public class DbContextBase : DbContext, IDbContext
    {
        private readonly Guid _instanceId;

        public DbContextBase(string nameOrConnectionString) : base(nameOrConnectionString)
        {
            _instanceId = Guid.NewGuid();
        }

        public Guid InstanceId
        {
            get { return _instanceId; }
        }

        public void ApplyStateChanges()
        {
            foreach (var dbEntityEntry in ChangeTracker.Entries())
            {
                var entityState = dbEntityEntry.Entity as IObjectState;
                if (entityState == null)
                    throw new InvalidCastException("All entites must implement the IObjectState interface, " +
                                                   "this interface must be implemented so each entites state can explicitely determined when updating graphs.");

                dbEntityEntry.State = StateHelper.ConvertState(entityState.State);
            }
        }

        public new IDbSet<T> Set<T>() where T : class
        {
            return base.Set<T>();
        }

        protected override void OnModelCreating(DbModelBuilder builder)
        {
            builder.Conventions.Remove<PluralizingTableNameConvention>();
            base.OnModelCreating(builder);
        }

        public override int SaveChanges()
        {
            ApplyStateChanges();
            return base.SaveChanges();
        }
    }

After:


    public class DbContextBase : DbContext, IDbContext
    {
        private readonly Guid _instanceId;

        public DbContextBase(string nameOrConnectionString) : base(nameOrConnectionString)
        {
            _instanceId = Guid.NewGuid();
        }

        public Guid InstanceId
        {
            get { return _instanceId; }
        }

        public void ApplyStateChanges()
        {
            foreach (DbEntityEntry dbEntityEntry in ChangeTracker.Entries())
            {
                var entityState = dbEntityEntry.Entity as IObjectState;
                if (entityState == null)
                    throw new InvalidCastException("All entites must implement the IObjectState interface, " +
                                                   "this interface must be implemented so each entites state can explicitely determined when updating graphs.");

                dbEntityEntry.State = StateHelper.ConvertState(entityState.State);
            }
        }

        public new IDbSet<T> Set<T>() where T : class
        {
            return base.Set<T>();
        }

        public override int SaveChanges()
        {
            ApplyStateChanges();
            return base.SaveChanges();
        }

        public override Task<int> SaveChangesAsync()
        {
            ApplyStateChanges();
            return base.SaveChangesAsync();
        }

        public override Task<int> SaveChangesAsync(CancellationToken cancellationToken)
        {
            ApplyStateChanges();
            return base.SaveChangesAsync(cancellationToken);
        }

        protected override void OnModelCreating(DbModelBuilder builder)
        {
            builder.Conventions.Remove<PluralizingTableNameConvention>();
            base.OnModelCreating(builder);
        }
    }

All that was needed here was to expose all the DbContext Async save operations so that we could use with our IUnitOfWork implementation, and also not forgetting to invoke our ApplyStateChanges so that we are managing the different states each entity could have when dealing with graphs.

Next up, are the enhancements made to our Repository.cs, so that our generic repositories can leverage the Async goodness as well.

Repostiory.Repository.cs

Before:


 public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
    {
        private readonly Guid _instanceId;
        internal IDbContext Context;
        internal IDbSet<TEntity> DbSet;

        public Repository(IDbContext context)
        {
            Context = context;
            DbSet = context.Set<TEntity>();
            _instanceId = Guid.NewGuid();
        }

        public Guid InstanceId
        {
            get { return _instanceId; }
        }

        public virtual TEntity FindById(object id)
        {
            return DbSet.Find(id);
        }

        public virtual void InsertGraph(TEntity entity)
        {
            DbSet.Add(entity);
        }

        public virtual void Update(TEntity entity)
        {
            DbSet.Attach(entity);
        }

        public virtual void Delete(object id)
        {
            var entity = DbSet.Find(id);
            ((IObjectState) entity).State = ObjectState.Deleted;
            Delete(entity);
        }

        public virtual void Delete(TEntity entity)
        {
            DbSet.Attach(entity);
            DbSet.Remove(entity);
        }

        public virtual void Insert(TEntity entity)
        {
            DbSet.Attach(entity);
        }

        public virtual IRepositoryQuery<TEntity> Query()
        {
            var repositoryGetFluentHelper = new RepositoryQuery<TEntity>(this);
            return repositoryGetFluentHelper;
        }

        internal IQueryable<TEntity> Get(
            Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            List<Expression<Func<TEntity, object>>> includeProperties = null,
            int? page = null,
            int? pageSize = null)
        {
            IQueryable<TEntity> query = DbSet;

            if (includeProperties != null)
                includeProperties.ForEach(i => query = query.Include(i));

            if (filter != null)
                query = query.Where(filter);

            if (orderBy != null)
                query = orderBy(query);

            if (page != null && pageSize != null)
                query = query
                    .Skip((page.Value - 1)*pageSize.Value)
                    .Take(pageSize.Value);

            var results = query;

            return results;
        }
    }

After:


    public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
    {
        private readonly Guid _instanceId;
        private readonly DbSet<TEntity> _dbSet;

        public Repository(IDbContext context)
        {
            _dbSet = context.Set<TEntity>();
            _instanceId = Guid.NewGuid();
        }

        public Guid InstanceId
        {
            get { return _instanceId; }
        }

        public virtual TEntity Find(params object[] keyValues)
        {
            return _dbSet.Find(keyValues);
        }

        public virtual async Task<TEntity> FindAsync(params object[] keyValues)
        {
            return await _dbSet.FindAsync(keyValues);
        }

        public virtual async Task<TEntity> FindAsync(CancellationToken cancellationToken, params object[] keyValues)
        {
            return await _dbSet.FindAsync(cancellationToken, keyValues);
        }

        public virtual IQueryable<TEntity> SqlQuery(string query, params object[] parameters)
        {
            return _dbSet.SqlQuery(query, parameters).AsQueryable();
        }

        public virtual void InsertGraph(TEntity entity)
        {
            _dbSet.Add(entity);
        }

        public virtual void Update(TEntity entity)
        {
            _dbSet.Attach(entity);
            ((IObjectState)entity).State = ObjectState.Modified;
        }

        public virtual void Delete(object id)
        {
            var entity = _dbSet.Find(id);
            Delete(entity);
        }

        public virtual void Delete(TEntity entity)
        {
            _dbSet.Attach(entity);
            ((IObjectState)entity).State = ObjectState.Deleted;
            _dbSet.Remove(entity);
        }

        public virtual void Insert(TEntity entity)
        {
            _dbSet.Attach(entity);
            ((IObjectState)entity).State = ObjectState.Added;
        }

        public virtual IRepositoryQuery<TEntity> Query()
        {
            var repositoryGetFluentHelper = new RepositoryQuery<TEntity>(this);
            return repositoryGetFluentHelper;
        }

        internal IQueryable<TEntity> Get(
            Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            List<Expression<Func<TEntity, object>>> includeProperties = null,
            int? page = null,
            int? pageSize = null)
        {
            IQueryable<TEntity> query = _dbSet;

            if (includeProperties != null)
            {
                includeProperties.ForEach(i => query = query.Include(i));
            }

            if (filter != null)
            {
                query = query.Where(filter);
            }

            if (orderBy != null)
            {
                query = orderBy(query);
            }

            if (page != null && pageSize != null)
            {
                query = query
                    .Skip((page.Value - 1)*pageSize.Value)
                    .Take(pageSize.Value);
            }
            return query;
        }

        internal async Task<IEnumerable<TEntity>> GetAsync(
                    Expression<Func<TEntity, bool>> filter = null,
                    Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
                    List<Expression<Func<TEntity, object>>> includeProperties = null,
                    int? page = null,
                    int? pageSize = null)
        {
            return Get(filter, orderBy, includeProperties, page, pageSize).AsEnumerable();
        }
    }

Here we’ve exposed the FindAsync methods from DbSet, so our Repositories can make use of them, and we’ve also wrapped implemented an Async implementation of our Get() method so that we can use it in our new Web Api ProductController.cs later.

Important note: here is that although our method is named GetAsync, it is not truly performing an Async interaction, this is due to the fact that if we were to use ToListAsync(), we would already executed the the query prior to OData applying it’s criteria to the execution plan e.g. if the OData query was requesting 10 records for page 2 of a grid from a Products table that had 1000 rows in it, ToListAsync() would have actually pulled a 1000 records from SQL to the web server and at that time do a skip 10 and take 20 from the collection of Products with 1000 objects. What we want is for this to happen on the SQL Server, meaning, SQL query the Products table, skip the first 10, and take next 10 records and only send those 10 records over to the web server, which will eventually surface into the Grid in the user’s browsers. Hence we are favoring payload size (true SQL Server side paging) going over the wire, vs. a true Async call to SQL.

Northwind.Web.Areas.Spa.Api.ProductController.cs

Before:


    public class ProductController : EntitySetController<Product, int>
    {
        private readonly IUnitOfWork _unitOfWork;

        public ProductController(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public override IQueryable<Product> Get()
        {
            return _unitOfWork.Repository<Product>().Query().Get();
        }

        protected override Product GetEntityByKey(int key)
        {
            return _unitOfWork.Repository<Product>().FindById(key);
        }

        protected override Product UpdateEntity(int key, Product update)
        {
            update.State = ObjectState.Modified;
            _unitOfWork.Repository<Product>().Update(update);
            _unitOfWork.Save();

            return update;
        }

        public override void Delete([FromODataUri] int key)
        {
            _unitOfWork.Repository<Product>().Delete(key);
            _unitOfWork.Save();
        }

        protected override void Dispose(bool disposing)
        {
            _unitOfWork.Dispose();
            base.Dispose(disposing);
        }
    }
 

After:

Note: Don’t be overwhelmed by how much more code there is in the “After” for our new ProductController that now inherits AsyncEntitySetController. I’ll explain later, what all the other Actions are there for. For now, please keep in mind there are only a few of these Actions that are actually required for the use case on the live demo site. The only Actions (methods) that are needed for our use case are as follows:

  • Task<IEnumerable> Get()
  • Task Get([FromODataUri] int key)
  • Task UpdateEntityAsync(int key, Product update)
  • Task Delete([FromODataUri] int key)

[ODataNullValue]
public class ProductController : AsyncEntitySetController&lt;Product, int&gt;
{
    private readonly IUnitOfWork _unitOfWork;

    public ProductController(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    protected override void Dispose(bool disposing)
    {
        _unitOfWork.Dispose();
        base.Dispose(disposing);
    }

    protected override int GetKey(Product entity)
    {
        return entity.ProductID;
    }

[Queryable]
public override async Task&lt;IEnumerable&lt;Product&gt;&gt; Get()
{
return await _unitOfWork.Repository&lt;Product&gt;().Query().GetAsync();
}

    [Queryable]
    public override async Task&lt;HttpResponseMessage&gt; Get([FromODataUri] int key)
    {
        var query = _unitOfWork.Repository&lt;Product&gt;().Query().Filter(x =&gt; x.ProductID == key).Get();
        return Request.CreateResponse(HttpStatusCode.OK, query);
    }

    ///// &lt;summary&gt;
    ///// Retrieve an entity by key from the entity set.
    ///// &lt;/summary&gt;
    ///// &lt;param name=&quot;key&quot;&gt;The entity key of the entity to retrieve.&lt;/param&gt;
    ///// &lt;returns&gt;A Task that contains the retrieved entity when it completes, or null if an entity with the specified entity key cannot be found in the entity set.&lt;/returns&gt;
    [Queryable]
    protected override async Task&lt;Product&gt; GetEntityByKeyAsync(int key)
    {
        return await _unitOfWork.Repository&lt;Product&gt;().FindAsync(key);
    }

    protected override async Task&lt;Product&gt; CreateEntityAsync(Product entity)
    {
        if (entity == null)
            throw new HttpResponseException(HttpStatusCode.BadRequest);
            
        _unitOfWork.Repository&lt;Product&gt;().Insert(entity);
        await _unitOfWork.SaveAsync();
        return entity;
    }

    protected override async Task&lt;Product&gt; UpdateEntityAsync(int key, Product update)
    {
        if (update == null)
            throw new HttpResponseException(HttpStatusCode.BadRequest);
            
        if (key != update.ProductID)
            throw new HttpResponseException(Request.CreateODataErrorResponse(HttpStatusCode.BadRequest, new ODataError { Message = &quot;The supplied key and the Product being updated do not match.&quot; }));

        try
        {
            update.State = ObjectState.Modified;
            _unitOfWork.Repository&lt;Product&gt;().Update(update);
            var x = await _unitOfWork.SaveAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            throw new HttpResponseException(HttpStatusCode.BadRequest);
        }
        return update;
    }

    // PATCH &lt;controller&gt;(key)
    /// &lt;summary&gt;
    /// Apply a partial update to an existing entity in the entity set.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;key&quot;&gt;The entity key of the entity to update.&lt;/param&gt;
    /// &lt;param name=&quot;patch&quot;&gt;The patch representing the partial update.&lt;/param&gt;
    /// &lt;returns&gt;A Task that contains the updated entity when it completes.&lt;/returns&gt;
    protected override async Task&lt;Product&gt; PatchEntityAsync(int key, Delta&lt;Product&gt; patch)
    {
        if (patch == null)
            throw new HttpResponseException(HttpStatusCode.BadRequest);

        if (key != patch.GetEntity().ProductID)
            throw Request.EntityNotFound();

        var entity = await _unitOfWork.Repository&lt;Product&gt;().FindAsync(key);

        if (entity == null)
            throw Request.EntityNotFound();

        try
        {
            patch.Patch(entity);
            await _unitOfWork.SaveAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            throw new HttpResponseException(HttpStatusCode.Conflict);
        }
        return entity;
    }

    public override async Task Delete([FromODataUri] int key)
    {
        var entity = await _unitOfWork.Repository&lt;Product&gt;().FindAsync(key);

        if (entity == null)
            throw Request.EntityNotFound();

        _unitOfWork.Repository&lt;Product&gt;().Delete(entity);

        try
        {
            await _unitOfWork.SaveAsync();
        }
        catch (Exception e)
        { 
            throw new HttpResponseException(
                new HttpResponseMessage(HttpStatusCode.Conflict)
                {
                    StatusCode = HttpStatusCode.Conflict, 
                    Content = new StringContent(e.Message), 
                    ReasonPhrase = e.InnerException.InnerException.Message
                });
        }
    }

    #region Links
    // Create a relation from Product to Category or Supplier, by creating a $link entity.
    // POST &lt;controller&gt;(key)/$links/Category
    // POST &lt;controller&gt;(key)/$links/Supplier
    /// &lt;summary&gt;
    /// Handle POST and PUT requests that attempt to create a link between two entities.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;key&quot;&gt;The key of the entity with the navigation property.&lt;/param&gt;
    /// &lt;param name=&quot;navigationProperty&quot;&gt;The name of the navigation property.&lt;/param&gt;
    /// &lt;param name=&quot;link&quot;&gt;The URI of the entity to link.&lt;/param&gt;
    /// &lt;returns&gt;A Task that completes when the link has been successfully created.&lt;/returns&gt;
    [AcceptVerbs(&quot;POST&quot;, &quot;PUT&quot;)]
    public override async Task CreateLink([FromODataUri] int key, string navigationProperty, [FromBody] Uri link)
    {
        var entity = await _unitOfWork.Repository&lt;Product&gt;().FindAsync(key);

        if (entity == null)
            throw Request.EntityNotFound();
            
        switch (navigationProperty)
        {
            case &quot;Category&quot;:
                var categoryKey = Request.GetKeyValue&lt;int&gt;(link);
                var category = await _unitOfWork.Repository&lt;Category&gt;().FindAsync(categoryKey);

                if (category == null)
                    throw Request.EntityNotFound();
                    
                    entity.Category = category;
                break;

            case &quot;Supplier&quot;:
                var supplierKey = Request.GetKeyValue&lt;int&gt;(link);
                var supplier = await _unitOfWork.Repository&lt;Supplier&gt;().FindAsync(supplierKey);

                if (supplier == null)
                    throw Request.EntityNotFound();
                    
                    entity.Supplier = supplier;
                break;

            default:
                await base.CreateLink(key, navigationProperty, link);
                break;
        }
        await _unitOfWork.SaveAsync();
    }

    // Remove a relation, by deleting a $link entity
    // DELETE &lt;controller&gt;(key)/$links/Category
    // DELETE &lt;controller&gt;(key)/$links/Supplier
    /// &lt;summary&gt;
    /// Handle DELETE requests that attempt to break a relationship between two entities.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;key&quot;&gt;The key of the entity with the navigation property.&lt;/param&gt;
    /// &lt;param name=&quot;relatedKey&quot;&gt;The key of the related entity.&lt;/param&gt;
    /// &lt;param name=&quot;navigationProperty&quot;&gt;The name of the navigation property.&lt;/param&gt;
    /// &lt;returns&gt;Task.&lt;/returns&gt;
    public override async Task DeleteLink([FromODataUri] int key, string relatedKey, string navigationProperty)
    {
        var entity = await _unitOfWork.Repository&lt;Product&gt;().FindAsync(key);

        if (entity == null)
            throw Request.EntityNotFound();

        switch (navigationProperty)
        {
            case &quot;Category&quot;:
                entity.Category = null;
                break;

            case &quot;Supplier&quot;:
                entity.Supplier = null;
                break;

            default:
                await base.DeleteLink(key, relatedKey, navigationProperty);
                break;
        }

        await _unitOfWork.SaveAsync();
    }

    // Remove a relation, by deleting a $link entity
    // DELETE &lt;controller&gt;(key)/$links/Category
    // DELETE &lt;controller&gt;(key)/$links/Supplier
    /// &lt;summary&gt;
    /// Handle DELETE requests that attempt to break a relationship between two entities.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;key&quot;&gt;The key of the entity with the navigation property.&lt;/param&gt;
    /// &lt;param name=&quot;navigationProperty&quot;&gt;The name of the navigation property.&lt;/param&gt;
    /// &lt;param name=&quot;link&quot;&gt;The URI of the entity to remove from the navigation property.&lt;/param&gt;
    /// &lt;returns&gt;Task.&lt;/returns&gt;
    public override async Task DeleteLink([FromODataUri] int key, string navigationProperty, [FromBody] Uri link)
    {
        var entity = await _unitOfWork.Repository&lt;Product&gt;().FindAsync(key);

        if (entity == null)
            throw Request.EntityNotFound();

        switch (navigationProperty)
        {
            case &quot;Category&quot;:
                entity.Category = null;
                break;

            case &quot;Supplier&quot;:
                entity.Supplier = null;
                break;

            default:
                await base.DeleteLink(key, navigationProperty, link);
                break;
        }

        await _unitOfWork.SaveAsync();
    }
    #endregion Links

    public override async Task&lt;HttpResponseMessage&gt; HandleUnmappedRequest(ODataPath odataPath)
    {
        //TODO: add logic and proper return values
        return Request.CreateResponse(HttpStatusCode.NoContent, odataPath);
    }

    #region Navigation Properties
    public async Task&lt;Category&gt; GetCategory(int key)
    {
        var entity = await _unitOfWork.Repository&lt;Product&gt;().FindAsync(key);

        if (entity == null)
            throw Request.EntityNotFound();
            
        return entity.Category;
    }

    public async Task&lt;Supplier&gt; GetSupplier(int key)
    {
        var entity = await _unitOfWork.Repository&lt;Product&gt;().FindAsync(key);

        if (entity == null)
            throw Request.EntityNotFound();
            
        return entity.Supplier;
    }
    #endregion Navigation Properties
}

Quickly looking at this, one can realize there is a lot more code than our pre-Async implementation. Well don’t be alarmed, there’s a lot of code here that wasn’t required to support our use case in the live demo (http://longle.azurewebsites.net), however we wanted to take the extra step so that we can really grasp on how to work with entity graphs with OData by leveraging the ?$expand query string parameter.

We’ll leave all the other that Actions that aren’t actually required for our use case on the live demo SPA as is, so we can see how to deep load your entity graph with OData and Web Api. We’ve included some pre-baked clickable OData URL’s (queries) on the View so that you can actually click and see the response payload in your browser (you’ll have to use Chrome or Firefox, IE has some catching up to do here).

*Click on image
10-9-2013 8-51-43 PM

Now let’s do a deep dive on the our Async Get() Action in our Controller.


[Queryable]
 
public override async Task&lt;IEnumerable&lt;Product&gt;&gt; Get()
{
    return await _unitOfWork.Repository&lt;Product&gt;().Query().GetAsync();
}
 

My initial thought when seeing this this Action (signature) is that it’s not IQueryable?! Which means that the SQL plan from EF has already been executed before OData has an opportunity to apply it’s criteria to the query plan! Well that’s not the case, we outfitted the Project with Glimpse and Glimpse EF6 to actually see what SQL queries were being sent over the wire.

So let’s take a look at the loading up our Kendo UI Grid with the awesomeness of Glimpse running. Since our View is built with Kendo UI, and we know it’s invoking Ajax calls to request data, we’ll click on the Ajax panel on the Glimpse HUD.

*Click on image
10-9-2013 7-30-56 PM

Now with the HUD automatically switching to standard view we can see all the Ajax requests that our View made, we are interested in the OData request that was made to hydrate our Kendo Grid.

*Click on image
10-9-2013 8-04-32 PM

After clicking on Inspect for the Ajax OData request, we see that menu buttons buttons that have tracing data for that request start to actual blink…! One of them being SQL, so let’s click on it.

*Click on image
10-9-2013 8-32-10 PM

Ladies and gentlemen, I kid you not, behold this is the actual SQL query that was from our Unit Of Work -> Repostiory -> Entity Framework 6 -> T-SQL, that was actually sent to SQL Server (actually in our case SQL Server CE, so that the live demo can be complete free with Azure Website without the need to pay for SQL Azure). BTW, we just scratching the surface of what Glimpse can do, the list is pretty much endless e.g. displays MVC Routes, Actions, Tracing, Environment Variables, MVC Views, and performance metrics for pretty much all of them, etc.

Now back to the topic at hand, we can definitively see that although our Action and our Repository are returning IEnumerable:

Get Action the Kendo UI Datasource is calling, which returns IEnumerable.


[Queryable] 
 
public override async Task&lt;IEnumerable&lt;Product&gt;&gt; Get()
{
    return await _unitOfWork.Repository&lt;Product&gt;().Query().GetAsync();
}
 

Repository method the Action is calling, which also returns IEnumerable.


        internal async Task&lt;IEnumerable&lt;TEntity&gt;&gt; GetAsync(
                    Expression&lt;Func&lt;TEntity, bool&gt;&gt; filter = null,
                    Func&lt;IQueryable&lt;TEntity&gt;, IOrderedQueryable&lt;TEntity&gt;&gt; orderBy = null,
                    List&lt;Expression&lt;Func&lt;TEntity, object&gt;&gt;&gt; includeProperties = null,
                    int? page = null,
                    int? pageSize = null)
        {
            return Get(filter, orderBy, includeProperties, page, pageSize).AsEnumerable();
        }
 

The query plan is still valid, meaning it’s selecting only the rows (10 records to be exact) that the Grid is requesting for page one (1) of the Grid. So how is this happening? Well we’ve decorated our action with the [Queryable] attribute, so OData and Web Api is able to perform it’s magic together during run-time in the ASP.NET HTTP pipeline.

T-SQL that’s being sent over the wire, courtesy of Glimpse EF6

 
 
SELECT TOP (10 /* @p__linq__0 */) 
    [Extent1].[Product ID] AS [Product ID], 
    [Extent1].[Product Name] AS [Product Name], 
    [Extent1].[Supplier ID] AS [Supplier ID], 
    [Extent1].[Category ID] AS [Category ID], 
    [Extent1].[Quantity Per Unit] AS [Quantity Per Unit], 
    [Extent1].[Unit Price] AS [Unit Price], 
    [Extent1].[Units In Stock] AS [Units In Stock], 
    [Extent1].[Units On Order] AS [Units On Order], 
    [Extent1].[Reorder Level] AS [Reorder Level], 
    [Extent1].[Discontinued] AS [Discontinued]
    FROM [Products] AS [Extent1]
    ORDER BY [Extent1].[Product ID] ASC
 

Now, let’s cover at a high-level on all the Actions that aren’t required for our live demo use case, which are mostly to support Navigation Properties e.g. Product.Supplier, Product.Category, etc.

The $expand query string parameter allows us to hydrate complex navigation property types. For example in our case when we query for a Product, and Product has a property of Category and we the Category to be hydrated with its data we would leverage the $expand querystring parameter to do this, click this Url : http://longle.azurewebsites.net/odata/Product/?$inlinecount=allpages&$orderby=ProductName&$skip=1&$top=2&$expand=Category&$select=ProductID,ProductName,Category/CategoryID,Category/CategoryName to see the $expand in action.

T-SQL that’s being sent over the wire, again, courtesy of Glimpse EF6

 
 
SELECT TOP (2 /* @p__linq__1 */) 
    [top].[Product ID] AS [Product ID], 
    [top].[C1] AS [C1], 
    [top].[C2] AS [C2], 
    [top].[Product Name] AS [Product Name], 
    [top].[C3] AS [C3], 
    [top].[C4] AS [C4], 
    [top].[C5] AS [C5], 
    [top].[C6] AS [C6], 
    [top].[Category Name] AS [Category Name], 
    [top].[C7] AS [C7], 
    [top].[Category ID] AS [Category ID], 
    [top].[C8] AS [C8]
    FROM ( SELECT [Project1].[Product ID] AS [Product ID], [Project1].[Product Name] AS [Product Name], [Project1].[Category ID] AS [Category ID], [Project1].[Category Name] AS [Category Name], [Project1].[C1] AS [C1], [Project1].[C2] AS [C2], [Project1].[C3] AS [C3], [Project1].[C4] AS [C4], [Project1].[C5] AS [C5], [Project1].[C6] AS [C6], [Project1].[C7] AS [C7], [Project1].[C8] AS [C8]
        FROM ( SELECT 
            [Extent1].[Product ID] AS [Product ID], 
            [Extent1].[Product Name] AS [Product Name], 
            [Extent1].[Category ID] AS [Category ID], 
            [Extent2].[Category Name] AS [Category Name], 
            N'ace5ad31-e3e9-4cde-9bb8-d75fced846fa' AS [C1], 
            N'ProductName' AS [C2], 
            N'ProductID' AS [C3], 
            N'Category' AS [C4], 
            N'ace5ad31-e3e9-4cde-9bb8-d75fced846fa' AS [C5], 
            N'CategoryName' AS [C6], 
            N'CategoryID' AS [C7], 
            CASE WHEN ([Extent1].[Category ID] IS NULL) THEN cast(1 as bit) ELSE cast(0 as bit) END AS [C8]
            FROM  [Products] AS [Extent1]
            LEFT OUTER JOIN [Categories] AS [Extent2] ON [Extent1].[Category ID] = [Extent2].[Category ID]
        )  AS [Project1]
        ORDER BY [Project1].[Product Name] ASC, [Project1].[Product ID] ASC
        OFFSET 1 /* @p__linq__0 */ ROWS 
    )  AS [top]
 

Product results with Categories hydrated

 
  
{
  &quot;odata.metadata&quot;:&quot;http://longle.azurewebsites.net/odata/$metadata#Product&amp;$select=ProductID,ProductName,Category/CategoryID,Category/CategoryName&quot;,&quot;odata.count&quot;:&quot;77&quot;,&quot;value&quot;:[
    {
      &quot;Category&quot;:{
        &quot;CategoryID&quot;:2,&quot;CategoryName&quot;:&quot;Condiments&quot;
      },&quot;ProductID&quot;:3,&quot;ProductName&quot;:&quot;Aniseed Syrup&quot;
    },{
      &quot;Category&quot;:{
        &quot;CategoryID&quot;:8,&quot;CategoryName&quot;:&quot;Seafood&quot;
      },&quot;ProductID&quot;:40,&quot;ProductName&quot;:&quot;Boston Crab Meat&quot;
    }
  ]
} 
 

We can really see the power of Web Api and OData now, we’re actually able to query for Products (skip the first and take the next two) and request that Category be hydrated but specifically only the CategoryId and Name and none of the other fields.

Sample Application Client Side (Kendo UI) Tweaks

We’ve polished the UI/UX a bit, relocated Edit, Edit Details, and Delete buttons out of the rows into the Grid Toolbar (header) to make better use of the Grid real estate, using Kendo’s Template Framework, which illustrates how flexible Kendo UI can be. The app has been upgraded to, Twitter Bootstrap as by leveraging the new out of the box MVC Project Templates in Visual Studio 2013 (Preview) and changing the Kendo UI theme to Bootstrap to match.

All Kendo Views which are remotely loaded on demand into the SPA are now actually MVC Razor Views, the Kendo Router remotely loads views by traditional MVC routes e.g.
{controller}/{action}/{id} vs. what was in the previous post (http://blog.longle.net/2013/06/17/mvc-4-kendo-ui-spa-with-layout-router-mvvm/) which was just serving up raw *.html pages. This has been a request for devs that are making the transition from server side MVC development into the SPA realm, and had .NET libraries they still wanted to make use of and leverage in their their Controllers, and Razor Views for SPA’s. Obviously, all Views and ViewModel binding on the client-side are done with with Kendo’s MVVM Framework.

Northwind.Web/Areas/Spa/Content/Views/products.html

Before (non Razor, just plain *.html pages were used for SPA):

 
@{
    ViewBag.Title = &quot;Products&quot;;
    Layout = &quot;&quot;;
}
&lt;div class=&quot;row&quot;&gt;
    &lt;div class=&quot;span5&quot;&gt;
        &lt;h2&gt;Technlogy Stack&lt;/h2&gt;
        &lt;h3&gt;&lt;a href=&quot;http://blog.longle.net&quot;&gt;blog.longle.net&lt;/a&gt;&lt;/h3&gt;
        &lt;p&gt;ASP.NET MVC 4, Web API, OData, Entity Framework 6 CTP, EntityFramework CE 6 RC1, Visual Studio 2013 Preview, Sql Server CE, Twitter Bootstrap, Kendo UI Web, Azure Website PaaS (&lt;a href=&quot;http://www.windowsazure.com/en-us/develop/net/aspnet/&quot; target=&quot;blank&quot;&gt;free!&lt;/a&gt;)&lt;/p&gt;
        &lt;br /&gt;
        &lt;p&gt;&lt;a class=&quot;btn&quot; href=&quot;http://go.microsoft.com/fwlink/?LinkId=301865&quot;&gt;Learn more &amp;raquo;&lt;/a&gt;&lt;/p&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;br /&gt;&lt;br /&gt;
&lt;div class=&quot;k-content&quot; style=&quot;width: 100%&quot;&gt;
    &lt;div id=&quot;view&quot;&gt;
        &lt;div id=&quot;productGrid&quot;
             data-role=&quot;grid&quot;
             data-sortable=&quot;true&quot;
             data-pageable=&quot;true&quot;
             data-filterable=&quot;true&quot;
             data-bind=&quot;source: dataSource, events: { dataBound: dataBound, change: onChange }&quot;
             data-editable=&quot;inline&quot;
             data-selectable=&quot;true&quot;
             data-toolbar='[ { template: $(&quot;#toolbar&quot;).html() } ]'
             data-columns='[
                    { field: &quot;ProductID&quot;, title: &quot;ID&quot;, width: &quot;50px&quot; },
                    { field: &quot;ProductName&quot;, title: &quot;Name&quot;},
                    { field: &quot;QuantityPerUnit&quot;, title: &quot;Quantity&quot;, width: &quot;200px&quot; },
                    { field: &quot;UnitsInStock&quot;, title: &quot;Stock&quot;, width: &quot;90px&quot; },
                    { field: &quot;UnitPrice&quot;, title: &quot;Price&quot;, format: &quot;{0:c}&quot;, width: &quot;100px&quot; },
                    { field: &quot;Discontinued&quot;, width: &quot;150px&quot; } ]'&gt;
        &lt;/div&gt;
    &lt;/div&gt;
    &lt;h3&gt;Use Chrome or Firefox and click on OData (queries) Urls below for example results.&lt;/h3&gt;
    &lt;ul&gt;
        &lt;li&gt;&lt;a href=&quot;/odata/$metadata&quot;&gt;/odata/$metadata&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;/odata/Product&quot;&gt;/odata/Product&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;/odata/Product/?$select=ProductID,ProductName&quot;&gt;/odata/Product/?$select=ProductID,ProductName&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;/odata/Product/?$orderby=ProductName&amp;$skip=1&amp;$top=2&quot;&gt;/odata/Product/?$orderby=ProductName&amp;$skip=1&amp;$top=2&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;/odata/Product/?$orderby=ProductName&amp;$skip=1&amp;$top=2&quot;&gt;/odata/Product/?$orderby=ProductName&amp;$skip=1&amp;$top=2&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;/odata/Product/?$inlinecount=allpages&amp;$filter=UnitPrice ge 20&quot;&gt;/odata/Product/?$inlinecount=allpages&amp;$filter=UnitPrice ge 20&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;/odata/Product/?$expand=Category&quot;&gt;/odata/Product/?$expand=Category&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;/odata/Product/?$expand=Category&amp;$select=ProductID,ProductName,Category/CategoryID,Category/CategoryName&quot;&gt;/odata/Product/?$expand=Category&amp;$select=ProductID,ProductName,Category/CategoryID,Category/CategoryName&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;/odata/Product/?$inlinecount=allpages&amp;$orderby=ProductName&amp;$skip=1&amp;$top=2&amp;$expand=Category&amp;$select=ProductID,ProductName,Category/CategoryID,Category/CategoryName&quot;&gt;/odata/Product/?$inlinecount=allpages&amp;$orderby=ProductName&amp;$skip=1&amp;$top=2&amp;$expand=Category&amp;$select=ProductID,ProductName,Category/CategoryID,Category/CategoryName&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
&lt;/div&gt;

&lt;script type=&quot;text/x-kendo-template&quot; id=&quot;toolbar&quot;&gt;
    &lt;div class=&quot;toolbar&quot;&gt;
        &lt;a class=&quot;k-button&quot; onclick=&quot;edit(event);&quot;&gt;&lt;span class=&quot;k-icon k-i-tick&quot;&gt;&lt;/span&gt;Edit&lt;/a&gt;
        &lt;a class=&quot;k-button&quot; onclick=&quot;destroy(event);&quot;&gt;&lt;span class=&quot;k-icon k-i-tick&quot;&gt;&lt;/span&gt;Delete&lt;/a&gt;
        &lt;a class=&quot;k-button&quot; onclick=&quot;details(event);&quot;&gt;&lt;span class=&quot;k-icon k-i-tick&quot;&gt;&lt;/span&gt;Edit Details&lt;/a&gt;
    &lt;/div&gt;
    &lt;div class=&quot;toolbar&quot; style=&quot;display:none&quot;&gt;
        &lt;a class=&quot;k-button&quot; onclick=&quot;save(event);&quot;&gt;&lt;span class=&quot;k-icon k-i-tick&quot;&gt;&lt;/span&gt;Save&lt;/a&gt;
        &lt;a class=&quot;k-button&quot; onclick=&quot;cancel(event);&quot;&gt;&lt;span class=&quot;k-icon k-i-tick&quot;&gt;&lt;/span&gt;Cancel&lt;/a&gt;
    &lt;/div&gt;
&lt;/script&gt;

&lt;script&gt;
    var lastSelectedDataItem;

    var save = function (event) {
        onClick(event, function (grid) {
            grid.saveRow();
            $(&quot;.toolbar&quot;).toggle();
        });
    };

    var cancel = function (event) {
        onClick(event, function (grid) {
            grid.cancelRow();
            $(&quot;.toolbar&quot;).toggle();
        });
    };

    var details = function (event) {
        onClick(event, function (grid, row, dataItem) {
            window.location.href = '#/edit/' + dataItem.ProductID;
        });
    };

    var edit = function (event) {
        onClick(event, function (grid, row) {
            grid.editRow(row);
            $(&quot;.toolbar&quot;).toggle();
        });
    };

    var destroy = function (event) {
        onClick(event, function (grid, row, dataItem) {
            grid.dataSource.remove(dataItem);
            grid.dataSource.sync();
        });
    };

    var onClick = function (event, delegate) {
        event.preventDefault();
        var grid = $(&quot;#productGrid&quot;).data(&quot;kendoGrid&quot;);
        var selectedRow = grid.select();
        var dataItem = grid.dataItem(selectedRow);
        if (selectedRow.length &gt; 0)
            delegate(grid, selectedRow, dataItem);
        else
            alert(&quot;Please select a row.&quot;);
    };

    var Product = kendo.data.Model.define({
        id: &quot;ProductID&quot;,
        fields: {
            ProductID: { type: &quot;number&quot;, editable: false, nullable: true },
            ProductName: { type: &quot;string&quot;, validation: { required: true } },
            QuantityPerUnit: { type: &quot;string&quot;, validation: { required: true } },
            UnitsInStock: { type: &quot;number&quot;, validation: { required: true } },
            UnitPrice: { type: &quot;number&quot;, validation: { required: true, min: 1 } },
            Discontinued: { type: &quot;boolean&quot; }
        }
    });

    var baseUrl = &quot;/odata/Product&quot;;

    var dataSource = new kendo.data.DataSource({
        type: &quot;odata&quot;,
        transport: {
            read: {
                url: baseUrl,
                dataType: &quot;json&quot;
            },
            update: {
                url: function (data) {
                    return baseUrl + &quot;(&quot; + data.ProductID + &quot;)&quot;;
                },
                dataType: &quot;json&quot;
            },
            destroy: {
                url: function (data) {
                    return baseUrl + &quot;(&quot; + data.ProductID + &quot;)&quot;;
                },
                dataType: &quot;json&quot;
            }
        },
        batch: false,
        serverPaging: true,
        serverSorting: true,
        serverFiltering: true,
        pageSize: 10,
        schema: {
            data: function (data) {
                return data.value;
            },
            total: function (data) {
                return data[&quot;odata.count&quot;];
            },
            errors: function (e) {
                return e.errors;
            },
            model: Product
        },
        error: function (e) {
            var responseJson = e.xhr.responseJSON;
            if (responseJson != undefined) {
                if (responseJson[&quot;odata.error&quot;] != undefined) {
                    var error = responseJson[&quot;odata.error&quot;];
                    var message = error.message.value + '\n\n' + error.innererror.message;
                    alert(message);
                }
            } else {
                alert(e.xhr.status + &quot;\n\n&quot; + e.xhr.responseText + &quot;\n\n&quot; + e.xhr.statusText);
            }
            this.read();
        }
    });

    var viewModel = kendo.observable({
        dataSource: dataSource,
        dataBound: function (arg) {
            if (lastSelectedDataItem == null) return; // check if there was a row that was selected
            var view = this.dataSource.view(); // get all the rows
            for (var i = 0; i &lt; view.length; i++) { // iterate through rows
                if (view[i].ProductID == lastSelectedDataItem.ProductID) { // find row with the lastSelectedProductd
                    var grid = arg.sender; // get the grid
                    grid.select(grid.table.find(&quot;tr[data-uid='&quot; + view[i].uid + &quot;']&quot;)); // set the selected row
                    break;
                }
            }
        },
        onChange: function (arg) {
            var grid = arg.sender;
            lastSelectedDataItem = grid.dataItem(grid.select());
        },
    });

    $(document).bind(&quot;viewSwtichedEvent&quot;, function (e, args) { // subscribe to the viewSwitchedEvent
        if (args.name == &quot;list&quot;) { // check if this view was switched too
            if (args.isRemotelyLoaded) { // check if this view was loaded for the first time (remotely from server)
                kendo.bind($(&quot;#view&quot;), viewModel); // bind the view to the model
            } else {// view already been loaded in cache
                viewModel.dataSource.read(); // refresh grid
            }
        }
    });

&lt;/script&gt;
&lt;style scoped&gt;
    #productGrid .k-toolbar {
        padding: .7em;
    }

    .toolbar {
        float: right;
    }
&lt;/style&gt;
 

10-9-2013 7-11-39 PM

Happy Coding…! 🙂

Live Demo: http://longle.azurewebsites.net
Download: https://genericunitofworkandrepositories.codeplex.com/

Telerik’s HTML5 Kendo UI Grid with Server Side Paging, Sorting & Filtering with MVC3, EF4 & Dynamic LINQ

Update: 06/18/2013 – It is recommended that you follow this post for Kendo UI Grid, Datasource filtering http://blog.longle.net/2013/06/18/mvc-4-web-api-odata-entity-framework-kendo-ui-grid-datasource-with-mvvm/

Update: 05/11/2012 – Added support for querying objects with child properties

Update: 04/24/2012 – Added recursion to the filters processing to support multiple search criterias on the same field while at the same time supporting searches across multiple fields.

I recently did a post Telerik’s HTML5 Kendo UI (Grid, Detail Template, TabStrip) which illustrated how to wire up their HTML5 Grid and handle server side paging. After doing so I quickly found myself needing to wire up the rest of server side bells and whistles e.g. sorting, filtering, etc.. Did some relentless googling and didn’t find any good resources on how to do this with MVC3 and EF4 so hence this blog post for the those of us that are doing just that. Rather than starting from scratch I’ll go ahead and continue where the my last blog left off.

So this first thing we need to do is configure our Kendo UI Grid for to do server side sorting and filtering so that we decompose what the requests pay loads look like coming from the Grid when performing these types of actions on it.

Configuring the Kendo UI Grid:


    $(document).ready(function () {
        var grid = $(&quot;#grid&quot;).kendoGrid({
            dataSource: {
                type: &quot;json&quot;,
                serverPaging: true,
                serverSorting: true,
                serverFiltering: true,
                allowUnsort: true,
                pageSize: 5,
                transport: {
                    read: {
                        url: &quot;Products/GetAll&quot;,
                        dataType: &quot;json&quot;,
                        type: &quot;POST&quot;,
                        contentType: &quot;application/json; charset=utf-8&quot;,
                        data: {}
                    },
                    parameterMap: function (options) {
                        return JSON.stringify(options);
                    }
                },
                schema: {
                    model: {
                        fields: {
                            ProductId: { type: &quot;number&quot; },
                            Name: { type: &quot;string&quot; },
                            Status: { type: &quot;string&quot; },
                            Created: { type: &quot;date&quot; }
                        }
                    },
                    data: &quot;Products&quot;,
                    total: &quot;TotalCount&quot;
                }
            },
            height: 700,
            sortable: true,
            groupable: true,
            pageable: true,
            filterable: true,
            columns: [
                    { field: &quot;ProductId&quot;, title: &quot;ProductId&quot; },
                    { field: &quot;ProductType&quot;, title: &quot;ProductType&quot; },
                    { field: &quot;Name&quot;, title: &quot;Name&quot; },
                    { field: &quot;Created&quot;, title: &quot;Created&quot;, format: &quot;{0:MM/dd/yyyy}&quot; }
                ],
            detailTemplate: kendo.template($(&quot;#template&quot;).html()),
            toolbar: kendo.template($(&quot;#toolBarTemplate&quot;).html()),
            detailInit: detailInit,
            dataBound: function () {
                this.expandRow(this.tbody.find(&quot;tr.k-master-row&quot;).first());
            }
        });

        var dropDown = grid.find(&quot;#requestType&quot;).kendoDropDownList({
            dataTextField: &quot;text&quot;,
            dataValueField: &quot;value&quot;,
            autoBind: false,
            optionLabel: &quot;All&quot;,
            dataSource: [
                    { text: &quot;Electronics&quot;, value: &quot;2&quot; },
                    { text: &quot;Machinery&quot;, value: &quot;1&quot; }
                ],
            change: function () {
                var value = this.value();
                if (value) {
                    grid.data(&quot;kendoGrid&quot;).dataSource.filter(
                        { field: &quot;ProductType&quot;, operator: &quot;eq&quot;, value: parseInt(value) });
                } else {
                    grid.data(&quot;kendoGrid&quot;).dataSource.filter({});
                }
            }
        });
    });

I’ve highlighted some of the major changes we made to our configuration which include setting up the Grid for server side actions: paging, sorting, filter, unsort and surfacing the filteration capabilities to the UI. Lines 54-72 is for setting up a Grid Toolbar which will contain a Kendo UI DrownDownList so that we can filter the Grid on ProductTypes which we will come back around to later on.

Now that we have the Grid configured for server side processing let’s take a quick look at what’s going down the wire in terms of pay loads for each of these actions so that we can mock up our models for these requests. When loading up IE Developer Tools (hit F12 or Tools > Developer Tools) and clicking on the Network Tab to start capturing network traffic we can see the actual pay load request for each of these actions.

So we can see that the pay load that is coming down the wire when a user performs a filter and sort on the grid is:


{&quot;take&quot;:5,&quot;skip&quot;:0,&quot;page&quot;:1,&quot;pageSize&quot;:5,&quot;group&quot;:[],&quot;filter&quot;:{&quot;filters&quot;:[{&quot;field&quot;:&quot;ProductType&quot;,&quot;operator&quot;:&quot;eq&quot;,&quot;value&quot;:&quot;3&quot;}],&quot;logic&quot;:&quot;and&quot;},&quot;sort&quot;:[{&quot;field&quot;:&quot;Name&quot;,&quot;dir&quot;:&quot;desc&quot;}]}

From this we can start mocking up our models needed for these types of Grid Actions for our Controller.


namespace MvcApplication3.Models
{
    public class GridFilter
    {
        public string Operator { get; set; }
        public string Field { get; set; }
        public string Value { get; set; }
    }

    public class GridFilters
    {
        public List&lt;GridFilter&gt; Filters { get; set; }
        public string Logic { get; set; }
    }

    public class GridSort
    {
        public string Field { get; set; }
        public string Dir { get; set; }
    }
}

Making changes to our Controller Action

We need to make changes to our existing Action on our Controller to support these new Grid objects that is being posted from our Grid when a user does a server side sort, filter, etc..


    public class ProductsController : Controller
    {
        [HttpPost]
        public JsonResult GetAll(int skip, int take, int page, int pageSize, 
            List&lt;GridSort&gt; sort = null, GridFilters filter = null)
        {
            var myDatabaseContext = new MyDatabaseContext();

            var products = myDatabaseContext.Products.AsQueryable();
            var totalCount = myDatabaseContext.Products.AsQueryable();

            if (filter != null &amp;&amp; (filter.Filters != null &amp;&amp; filter.Filters.Count &gt; 0))
            {
                string whereClause = null;
                var parameters = new List&lt;object&gt;();
                var filters = filter.Filters;

                for (var i = 0; i &lt; filters.Count; i++)
                {
                    if (i == 0)
                        whereClause += string.Format(&quot; {0}&quot;, 
                            BuildWhereClause&lt;Product&gt;(i, filter.Logic, filters[i], 
                            parameters));
                    else
                        whereClause += string.Format(&quot; {0} {1}&quot;, 
                            ToLinqOperator(filter.Logic), 
                            BuildWhereClause&lt;Product&gt;(i, filter.Logic, filters[i], 
                            parameters));
                }

                products = products.Where(whereClause, parameters.ToArray());
                totalCount = products.Where(whereClause, parameters.ToArray());
            }

            if (sort != null &amp;&amp; sort.Count &gt; 0)
                foreach (var s in sort)
                {
                    s.Field = (s.Field == &quot;ProductType&quot;) ? &quot;ProductTypeId&quot; : s.Field;
                    products = products.OrderBy(s.Field + &quot; &quot; + s.Dir);
                }

            products = products.Skip(skip).Take(take);

            List&lt;Product&gt; productList = products.ToList();

            var productViewModels = new List&lt;ProductViewModel.Product&gt;();

            foreach (var p in productList)
            {
                productViewModels.Add(new ProductViewModel.Product
                                            {
                                                Completed = p.Completed.Date,
                                                CompletedBy = p.CompletedBy,
                                                Created = p.Created.Date,
                                                CreatedBy = p.CreatedBy,
                                                Name = p.Name,
                                                ProductId = p.ProductId,
                                                ProductType = p.ProductType.Name,
                                                ProductDetails = p.ProductDetails,
                                                Status = p.Status,
                                                Updated = p.Updated.Date,
                                                UpdatedBy = p.UpdatedBy
                                            });
            }

            return Json(
                new ProductViewModel
                    {
                        Products = productViewModels,
                        TotalCount = totalCount.Count()
                    });
        }

        public static string BuildWhereClause&lt;T&gt;(int index, string logic, 
            GridFilter filter, List&lt;object&gt; parameters)
        {
            var entityType = (typeof(T));
            var property = entityType.GetProperty(filter.Field);

            switch (filter.Operator.ToLower())
            {
                case &quot;eq&quot;:
                case &quot;neq&quot;:
                case &quot;gte&quot;:
                case &quot;gt&quot;:
                case &quot;lte&quot;:
                case &quot;lt&quot;:
                    if (typeof(DateTime).IsAssignableFrom(property.PropertyType))
                    {
                        parameters.Add(DateTime.Parse(filter.Value).Date);
                        return string.Format(&quot;EntityFunctions.TruncateTime({0}){1}@{2}&quot;, 
                            filter.Field, 
                            ToLinqOperator(filter.Operator), 
                            index);
                    }
                    if (typeof(int).IsAssignableFrom(property.PropertyType))
                    {
                        parameters.Add(int.Parse(filter.Value));
                        return string.Format(&quot;{0}{1}@{2}&quot;, 
                            filter.Field, 
                            ToLinqOperator(filter.Operator), 
                            index);
                    }
                    parameters.Add(filter.Value);
                    return string.Format(&quot;{0}{1}@{2}&quot;, 
                        filter.Field, 
                        ToLinqOperator(filter.Operator), 
                        index);
                case &quot;startswith&quot;:
                    parameters.Add(filter.Value);
                    return string.Format(&quot;{0}.StartsWith(&quot; + &quot;@{1})&quot;, 
                        filter.Field, 
                        index);
                case &quot;endswith&quot;:
                    parameters.Add(filter.Value);
                    return string.Format(&quot;{0}.EndsWith(&quot; + &quot;@{1})&quot;, 
                        filter.Field, 
                        index);
                case &quot;contains&quot;:
                    parameters.Add(filter.Value);
                    return string.Format(&quot;{0}.Contains(&quot; + &quot;@{1})&quot;, 
                        filter.Field, 
                        index);
                default:
                    throw new ArgumentException(
                        &quot;This operator is not yet supported for this Grid&quot;, 
                        filter.Operator);
            }
        }

        public static string ToLinqOperator(string @operator)
        {
            switch (@operator.ToLower())
            {
                case &quot;eq&quot;: return &quot; == &quot;;
                case &quot;neq&quot;: return &quot; != &quot;;
                case &quot;gte&quot;: return &quot; &gt;= &quot;;
                case &quot;gt&quot;: return &quot; &gt; &quot;;
                case &quot;lte&quot;: return &quot; &lt;= &quot;;
                case &quot;lt&quot;: return &quot; &lt; &quot;;
                case &quot;or&quot;: return &quot; || &quot;;
                case &quot;and&quot;: return &quot; &amp;&amp; &quot;;
                default: return null;
            }
        }

        public JsonResult GetProductDetails(int skip, int take, int page, 
            int pageSize, string group)
        {
            var myDatabaseContext = new MyDatabaseContext();

            var productDetails = myDatabaseContext.ProductDetails
                .OrderBy(p =&gt; p.ProducDetailtId);

            return Json(
                new ProductDetailsViewModel
                    {
                        ProductDetails = productDetails.Skip(skip).Take(take),
                        TotalCount = productDetails.Count()
                    },
                JsonRequestBehavior.AllowGet);
        }
    }

Note: Instead of downloading the LINQ Dynamic Query Library, you may want to actually download the sample application for this post because the DynamicQueryable.cs class from the Linq Dynamic Libray has been slightly modified to handle EntityFunctions to support string search actions from our Grid such as Contains, StartsWidth and EndsWith string searches.

A few quick notes in regards to our changes to our Action on our Controller to now support complete server side processing of paging, sorting and filtering.

  • BuildWhereClause<T>(int index, string logic, GridFilter filter, List parameters)
    This helper method will build our our where clauses and predicates so tha we can chain them up and pass them into Dynamic LINQ.

  • ToLinqOperator(string @operator)

    This helper method will convert operators that are sent from our Grid to C# operators that Dynamic LINQ will understand and convert them for us

  • Lines 48-64, here we are iterating through the results to trim off the timestamp off of any properties that are of type datetime, so that when we do any grouping or filtering from the grid the timestamp of these fields are ignored.

                foreach (var p in productList)
                {
                    productViewModels.Add(new ProductViewModel.Product
                                                {
                                                    Completed = p.Completed.Date,
                                                    CompletedBy = p.CompletedBy,
                                                    Created = p.Created.Date,
                                                    CreatedBy = p.CreatedBy,
                                                    Name = p.Name,
                                                    ProductId = p.ProductId,
                                                    ProductType = p.ProductType.Name,
                                                    ProductDetails = p.ProductDetails,
                                                    Status = p.Status,
                                                    Updated = p.Updated.Date,
                                                    UpdatedBy = p.UpdatedBy
                                                });
                }
    
  • Lines 88-103, here we are checking against the type of the column (property) that we are searching against so that we can convert the search criteria to the appropriate type. Currently we are supporting searches against types of string, datetime and int. If you need to add more types simply enhance this section of the implementation.

                        if (typeof(DateTime).IsAssignableFrom(property.PropertyType))
                        {
                            parameters.Add(DateTime.Parse(filter.Value).Date);
                            return string.Format(&quot;EntityFunctions.TruncateTime({0}){1}@{2}&quot;, 
                                filter.Field, 
                                ToLinqOperator(filter.Operator), 
                                index);
                        }
                        if (typeof(int).IsAssignableFrom(property.PropertyType))
                        {
                            parameters.Add(int.Parse(filter.Value));
                            return string.Format(&quot;{0}{1}@{2}&quot;, 
                                filter.Field, 
                                ToLinqOperator(filter.Operator), 
                                index);
                        }
                        parameters.Add(filter.Value);
    
    
  • Lines 109-123, here we are just framing up the different queries for string searches from the Grid. The Grid supports StartsWith, Contains, and EndsWith.

                    case &quot;startswith&quot;:
                        parameters.Add(filter.Value);
                        return string.Format(&quot;{0}.StartsWith(&quot; + &quot;@{1})&quot;, 
                            filter.Field, 
                            index);
                    case &quot;endswith&quot;:
                        parameters.Add(filter.Value);
                        return string.Format(&quot;{0}.EndsWith(&quot; + &quot;@{1})&quot;, 
                            filter.Field, 
                            index);
                    case &quot;contains&quot;:
                        parameters.Add(filter.Value);
                        return string.Format(&quot;{0}.Contains(&quot; + &quot;@{1})&quot;, 
                            filter.Field, 
                            index);
    

    As you can see in the screenshot right below these are the current string search capabilites that the Grid has.

Great, let’s run a few searches from the Grid now.

  • Search on ProductId: 3

  • Search on Created Date: 04/20/2013

  • Search on Created Date >= 04/15/2012 and Name containing “sample product 3”

    Voila! Our controller only returns 3 records which assert our test case and are all of Created date >= 04/20/2012 and all contain the string “sample product 3” in the name.

Update: 04/24/2012

Added recursion to the filters processing to support multiple search criterias on the same field while at the same time supporting searches across multiple fields.

 

        [HttpPost]
        public JsonResult GetAll(int skip, int take, int page, int pageSize, 
            List&lt;GridSort&gt; sort = null, GridFilter filter = null)
        {
            var myDatabaseContext = new MyDatabaseContext();

            var products = myDatabaseContext.Products.AsQueryable();
            var totalCount = myDatabaseContext.Products.AsQueryable();

            if (filter != null &amp;&amp; (filter.Filters != null &amp;&amp; filter.Filters.Count &gt; 0))
            {
                ProcessFilters(filter, ref products);
                totalCount = products;
            }

            if (sort != null &amp;&amp; sort.Count &gt; 0)
                foreach (var s in sort)
                {
                    s.Field = (s.Field == &quot;ProductType&quot;) ? &quot;ProductTypeId&quot; : s.Field;
                    products = products.OrderBy(s.Field + &quot; &quot; + s.Dir);
                }

            products = products.Skip(skip).Take(take);

            List&lt;Product&gt; productList = products.ToList();

            var productViewModels = new List&lt;ProductViewModel.Product&gt;();

            foreach (var p in productList)
            {
                productViewModels.Add(new ProductViewModel.Product
                                            {
                                                Completed = p.Completed.Date,
                                                CompletedBy = p.CompletedBy,
                                                Created = p.Created.Date,
                                                CreatedBy = p.CreatedBy,
                                                Name = p.Name,
                                                ProductId = p.ProductId,
                                                ProductType = p.ProductType.Name,
                                                ProductDetails = p.ProductDetails,
                                                Status = p.Status,
                                                Updated = p.Updated.Date,
                                                UpdatedBy = p.UpdatedBy
                                            });
            }

            return Json(
                new ProductViewModel
                    {
                        Products = productViewModels,
                        TotalCount = totalCount.Count()
                    });
        }

        public static void ProcessFilters(GridFilter filter, ref IQueryable&lt;Product&gt; queryable)
        {
            var whereClause = string.Empty;
            var filters = filter.Filters;
            var parameters = new List&lt;object&gt;();
            for (int i = 0; i &lt; filters.Count; i++)
            {
                var f = filters[i];

                if (f.Filters == null)
                {
                    if (i == 0)
                        whereClause += BuildWhereClause&lt;Product&gt;(f, i, parameters) + &quot; &quot;;
                    if (i != 0)
                        whereClause += ToLinqOperator(filter.Logic) + 
                            BuildWhereClause&lt;Product&gt;(f, i, parameters) + &quot; &quot;;
                    if (i == (filters.Count - 1))
                    {
                        CleanUp(ref whereClause);
                        queryable = queryable.Where(whereClause, parameters.ToArray());
                    }
                }
                else
                    ProcessFilters(f, ref queryable);
            }
        }

Looks like our server side paging, sorting and filteration is golden!

Update: 05/11/2012- Added support for querying objects with child properties


    public static class GridHelper
    {
        public static void ProcessFilters&lt;T&gt;(GridFilter filter, ref IQueryable&lt;T&gt; queryable)
        {
            var whereClause = string.Empty;
            var filters = filter.Filters;
            var parameters = new List&lt;object&gt;();
            for (int i = 0; i &lt; filters.Count; i++)
            {
                var f = filters[i];

                if (f.Filters == null)
                {
                    if (i == 0)
                        whereClause += BuildWherePredicate&lt;T&gt;(f, i, parameters) + &quot; &quot;;
                    if (i != 0)
                        whereClause += ToLinqOperator(filter.Logic) + BuildWherePredicate&lt;T&gt;(f, i, parameters) + &quot; &quot;;
                    if (i == (filters.Count - 1))
                    {
                        TrimWherePredicate(ref whereClause);
                        queryable = queryable.Where(whereClause, parameters.ToArray());
                    }
                }
                else
                    ProcessFilters(f, ref queryable);
            }
        }

        public static string TrimWherePredicate(ref string whereClause)
        {
            switch (whereClause.Trim().Substring(0, 2).ToLower())
            {
                case &quot;&amp;&amp;&quot;:
                    whereClause = whereClause.Trim().Remove(0, 2);
                    break;
                case &quot;||&quot;:
                    whereClause = whereClause.Trim().Remove(0, 2);
                    break;
            }

            return whereClause;
        }

        public static string BuildWherePredicate&lt;T&gt;(GridFilter filter, int index, List&lt;object&gt; parameters)
        {
            var entityType = (typeof(T));
            PropertyInfo property;
            
            if(filter.Field.Contains(&quot;.&quot;))
                property = GetNestedProp&lt;T&gt;(filter.Field);
            else 
                property = entityType.GetProperty(filter.Field);
            
            var parameterIndex = parameters.Count;

            switch (filter.Operator.ToLower())
            {
                case &quot;eq&quot;:
                case &quot;neq&quot;:
                case &quot;gte&quot;:
                case &quot;gt&quot;:
                case &quot;lte&quot;:
                case &quot;lt&quot;:
                    if (typeof(DateTime).IsAssignableFrom(property.PropertyType))
                    {
                        parameters.Add(DateTime.Parse(filter.Value).Date);
                        return string.Format(&quot;EntityFunctions.TruncateTime(&quot; + filter.Field + &quot;)&quot; + ToLinqOperator(filter.Operator) + &quot;@&quot; + parameterIndex);
                    }
                    if (typeof(int).IsAssignableFrom(property.PropertyType))
                    {
                        parameters.Add(int.Parse(filter.Value));
                        return string.Format(filter.Field + ToLinqOperator(filter.Operator) + &quot;@&quot; + parameterIndex);
                    }
                    parameters.Add(filter.Value);
                    return string.Format(filter.Field + ToLinqOperator(filter.Operator) + &quot;@&quot; + parameterIndex);
                case &quot;startswith&quot;:
                    parameters.Add(filter.Value);
                    return filter.Field + &quot;.StartsWith(&quot; + &quot;@&quot; + parameterIndex + &quot;)&quot;;
                case &quot;endswith&quot;:
                    parameters.Add(filter.Value);
                    return filter.Field + &quot;.EndsWith(&quot; + &quot;@&quot; + parameterIndex + &quot;)&quot;;
                case &quot;contains&quot;:
                    parameters.Add(filter.Value);
                    return filter.Field + &quot;.Contains(&quot; + &quot;@&quot; + parameterIndex + &quot;)&quot;;
                default:
                    throw new ArgumentException(&quot;This operator is not yet supported for this Grid&quot;, filter.Operator);
            }
        }

        public static string ToLinqOperator(string @operator)
        {
            switch (@operator.ToLower())
            {
                case &quot;eq&quot;:
                    return &quot; == &quot;;
                case &quot;neq&quot;:
                    return &quot; != &quot;;
                case &quot;gte&quot;:
                    return &quot; &gt;= &quot;;
                case &quot;gt&quot;:
                    return &quot; &gt; &quot;;
                case &quot;lte&quot;:
                    return &quot; &lt;= &quot;;
                case &quot;lt&quot;:
                    return &quot; &lt; &quot;;
                case &quot;or&quot;:
                    return &quot; || &quot;;
                case &quot;and&quot;:
                    return &quot; &amp;&amp; &quot;;
                default:
                    return null;
            }
        }

        public static PropertyInfo GetNestedProp&lt;T&gt;(String name)
        {
            PropertyInfo info = null;
            var type = (typeof(T));
            foreach(var prop in name.Split('.'))
            {
                info = type.GetProperty(prop);
                type = info.PropertyType;
            }
            return info;
        }
    }

Happy Coding…! 🙂

Download sample application: https://skydrive.live.com/redir.aspx?cid=949a1c97c2a17906&resid=949A1C97C2A17906!465&parid=949A1C97C2A17906!361

https://drive.google.com/file/d/0B91gwLeUpEWBU2tnN0dNeVhSTzA/view?usp=sharing