Skip to content

Instantly share code, notes, and snippets.

@danielkillyevo
Created September 26, 2013 21:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielkillyevo/6720711 to your computer and use it in GitHub Desktop.
Save danielkillyevo/6720711 to your computer and use it in GitHub Desktop.
Generic OData WebAPI controller
public class BaseOdataController<TRepository, TEntity> : EntitySetController<TEntity, int>
where TRepository : IRepository<TEntity>
where TEntity : class
{
private readonly IUnitOfWork _unitOfWork;
private readonly TRepository _repository;
public BaseOdataController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_repository = _unitOfWork.GetRepository<TRepository>();
}
public override System.Linq.IQueryable<TEntity> Get()
{
return _repository.Get();
}
protected override TEntity GetEntityByKey(int key)
{
return _repository.Get(key);
}
protected override TEntity CreateEntity(TEntity entity)
{
_repository.Add(entity);
_unitOfWork.Commit();
return entity;
}
protected override TEntity UpdateEntity(int key, TEntity update)
{
var exists = _repository.Get(key) != null;
if (!exists)
throw new HttpResponseException(HttpStatusCode.NotFound);
_repository.Update(update);
_unitOfWork.Commit();
return update;
}
protected override TEntity PatchEntity(int key, Delta<TEntity> patch)
{
var entity = _repository.Get(key);
if (entity == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
patch.Patch(entity);
_unitOfWork.Commit();
return entity;
}
public override void Delete([FromODataUri]int key)
{
var entity = _repository.Get(key);
if (entity == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
_repository.Remove(entity);
_unitOfWork.Commit();
}
}
public class TechnologyController : BaseOdataController<ITechnologyRepository, Technology>
{
public TechnologyController(IUnitOfWork unitOfWork) : base(unitOfWork)
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment