Generic DbContext with REST methods

Simple generic wrapper to put CRUD on top of a class to use for a Web API or for data binding.

using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
/// <summary>
/// Bit bucket class
/// </summary>
public class Contact
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}
/// <summary>
/// Generic RESTish dbcontext.
/// </summary>
public class ContactContext : codewarren.com.SimpleContext<Contact> { }
namespace codewarren.com
{
    /// <summary>
    /// Class that  puts generic REST type methods on top of a class.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class SimpleContext<T> : DbContext where T : class
    {
        public DbSet<T> Items { get; set; }
        public List<T> Get()
        {
            return Items.ToList();
        }
        public T Get(int id)
        {
            return Items.Find(id);
        }
        public void Put(T item)
        {
            Items.Attach(item);
            Entry(item).State = EntityState.Modified;
            SaveChanges();
        }
        public void Post(T item)
        {
            Items.Add(item);
            SaveChanges();
        }
        public void Delete(int id)
        {
            Delete(Get(id));
        }
        public void Delete(T item)
        {
            Items.Attach(item);
            Entry(item).State = EntityState.Deleted;
            SaveChanges();
        }
    }
}

Here is a ApiController that makes use of it.

using System.Collections.Generic;
using System.Web.Http;

public class GenericController<T> :  ApiController where T: class 
{
    private readonly SimpleContext<T> _context = new SimpleContext<T>();

    public List<T> Get()
    {
        return _context.Get();
    }
    public T Get(int id)
    {
        return _context.Get(id);
    }
    public void Post([FromBody]T t)
    {
        _context.Post(t);
    }
    public void Put([FromBody]T t)
    {
        _context.Put(t);
    }
    public void Delete(int id)
    {
        _context.Delete(id);
    }
}
public class ContactController : GenericController<Contact> {}



Leave a comment