Skip to main content

ASP.NET Boilerplate: how to create a custom repository

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.

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


At this point, is needed to inject the dependency in the services.
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

Popular posts from this blog

How to use Font Awesome with IText

This post is about on how to use Font Awesome with IText library to generate awesome icons in our PDF documents. In this post, we are using  ITextSharp , a C# port for IText, but those are the same functionalities.

ASP.NET Boilerplate: an alternative guide to integrate Swagger

Swagger is an excellent tool for API exploration of our RESTful APIs. In this post, we'll cover how to integrate and setup Swagger in an  ASP.NET Boilerplate (ABP) application (with ASP.NET MVC 5.x framework), to provide client-side documentation of its ABP application services. Most of all, this is an alternative documentation to the proposed in its official web site.