ASP.NET Boilerplate (ABP) includes support for the automatic or generic creation of repositories to perform database operations. These repository implementations are enough in most cases but sometimes is needed to create custom repositories for some complex entities. This post is about how to create a custom repository.
When a repository is created, is possible to override the base methods or add new ones. To accomplish it, create an interface that inherits from
Next, is needed to create a class that inherits from MyProjectRepositoryBase and implements the previous interface.
At this point, is needed to inject the dependency in the services.
ABP repositories are enough in most cases and they are suggested to use it for as long as possible. However, complex entities may need to create custom implementations. When you create a repository you must follow the best practices suggested by ABP.
How to create a repository
When a repository is created, is possible to override the base methods or add new ones. To accomplish it, create an interface that inherits from
IRepository
.namespace DemoABP.EntityFramework.Repositories { public interface IPersonRepository : IRepository<Person> { Person GetWithInclude(int id); } }
Next, is needed to create a class that inherits from MyProjectRepositoryBase and implements the previous interface.
namespace DemoABP.EntityFramework.Repositories { public class PersonRepository : DemoABPRepositoryBase<Person>, IPersonRepository { public PersonRepository(IDbContextProvider<DemoABPDbContext> dbContextProvider) : base(dbContextProvider) { } // Override base implementation of GetAll method public override IQueryable<task> GetAll() { //... } // Add new method to this repository public Person GetWithInclude(int id) { return GetAll().Include(p => p.Address).Single(p => p.Id == id); } } }
How to use the repository
namespace DemoABP.Services { public class PersonAppService : ApplicationService, IPersonAppService { private readonly IPersonRepository _personRepository; public PersonAppService(IPersonRepository personRepository) { _personRepository = personRepository; } } }
Conclusions
ABP repositories are enough in most cases and they are suggested to use it for as long as possible. However, complex entities may need to create custom implementations. When you create a repository you must follow the best practices suggested by ABP.
Comments
Post a Comment