Skip to content

Instantly share code, notes, and snippets.

Created January 18, 2014 05:51
Show Gist options
  • Save anonymous/8486727 to your computer and use it in GitHub Desktop.
Save anonymous/8486727 to your computer and use it in GitHub Desktop.
WebAPI 2: DTO ModelFactory which has been refactored to include the creation of HATEOAS URIs-- HyperMedia Links NOTE: we were not able to use automapper to Map between Entities and DTO's because we wanted to create Hypertext URIs for the DTOs inside the Factory. So we opted to use the Factory Pattern for the creation of our DTO's
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CountingKs.Data.Entities;
using System.Web.Http.Routing;
using System.Net.Http;
namespace CountingKs.Models
{
//using a Model Factory, we have only one place to handling Mapping from
//Database entities to DTO's
public class ModelFactory
{
private UrlHelper _urlHelper;
//LEN NOTE: THE REASON WE DID NOT USE AUTOMAPPER IS BECAUSE WE WANTED TO USE THE REQUEST
//AND THE URL HELPER TO AID US IN CREATING OUR HYPERLINKS
public ModelFactory( HttpRequestMessage request )
{
//Remember to use the Url helper for WebAPI
//which is in System.Web.Http.Routing
_urlHelper = new UrlHelper(request); //this will help us to build
//the URLs for developer API discovery
}
public FoodModel Create( Food food )
{
return new FoodModel()
{
//get an url for the Food roud and supply the id of the food that we're returning
Url = _urlHelper.Link("Food", new { foodid = food.Id }),
Description = food.Description,
Measures = food.Measures.Select(m => Create(m))
};
}
public MeasureModel Create( Measure measure )
{
return new MeasureModel()
{
Url = _urlHelper.Link("Measures", new { foodid = measure.Food.Id, id = measure.Id }),
Description = measure.Description,
Calories = Math.Round(measure.Calories)
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment