Created
July 26, 2012 12:48
-
-
Save AdrianJSClark/3181844 to your computer and use it in GitHub Desktop.
Changes I'd make to Damian's blog post example from http://blog.damianbrady.com.au/2012/07/24/a-generic-repository-and-unit-of-work-implementation-for-entity-framework/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) { } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IUnitOfWork : IDisposable | |
{ | |
int SaveChanges(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment