Skip to content

Instantly share code, notes, and snippets.

@AdrianJSClark
Created July 26, 2012 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdrianJSClark/3181844 to your computer and use it in GitHub Desktop.
Save AdrianJSClark/3181844 to your computer and use it in GitHub Desktop.
public interface IExampleContext
{
IDbSet<Customer> Customers { get; set; }
}
public class ExampleContext : DbContext, IExampleContext, IUnitOfWork
{
public CustomerContext(string nameOrConn) : base(nameOrConn) { }
IDbSet<Customer> Customers { get; set; }
}
public class CustomerController : Controller
{
private readonly IUnitOfWork uow;
private readonly CustomerRepository customerRepository;
public CustomerController(IUnitOfWork uow, CustomerRepository customerRepository)
{
this.uow = uow;
this.customerRepository = customerRepository;
}
public ActionResult Edit(CustomerViewModel model)
{
var customer = customerRepository.GetById(model.Id);
// Validate & map viewmodel to model here
uow.SaveChanges();
}
}
public class GenericRepository<TContext, TEntity> : IGenericRepository<TEntity>
where TContext : IExampleContext
where TEntity : class
{
protected TContext _context;
/// <summary>
/// Constructor that takes a context
/// </summary>
/// <param name="context">An established data context</param>
public GenericRepository(TContext context)
{
_context = context;
}
// INSERT REST OF GENERIC REPOSITORY HERE
}
public class CustomerRepository : GenericRepository<IExampleContext, Customer>
{
public CustomerRepository(IExampleContext context) : base(context) { }
}
public interface IUnitOfWork : IDisposable
{
int SaveChanges();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment