1110
1110

Reputation: 6829

How to add additional entity specific method in generic repository

I have followed this tutorial and I learned about generic repository and unit of work.
But I am not clear with entity specific methods.
For example I have entities Country and City.
By using generic repository I can use Get() or GetById() which will return me country or city:

 var countries = unitOfWork.CountryRepository.Get();
 var cities = unitOfWork.CityRepository.Get();

But Country have a CountryCode field and I want to get country by that field so I suppose that I have to add new method in generic repository class and call it like:

var countries = unitOfWork.CountryRepository.GetByCountryCode(string code);

but that means that I can also do this:

var countries = unitOfWork.CityRepository.GetByCountryCode(string code);

I am confused here and I know that I miss something.
How can I use generic repository and add additional entity specific methods?

UPDATE

I create repository class with additional method:

public class CountryRepository : GenericRepository<Country>
    {
        public CountryRepository(MainContext context) : base(context) { }

        public virtual Country GetByCode(string code)
        {
            return dbSet.Where(c => c.Code == code).First();
        }
    }

In UnitOfWork.cs

public class UnitOfWork : IDisposable
    {
        private MainContext context = new MainContext();        
        private ApplicationUserRepository applicationUserRepository;
        private CountryRepository countryRepository;

        public GenericRepository<Country> CountryRepository
        {
            get
            {

                if (this.countryRepository == null)
                {
                    this.countryRepository = new CountryRepository(context);
                }
                return countryRepository;
            }
        }

But from controller I don't see GetByCode():

var country = unitOfWork.CountryRepository. // no GetByCode()

Upvotes: 1

Views: 1418

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54427

If you want methods specific to an entity then you declare those methods in that entity's repository specifically, i.e. your GetByCountryCode method is declared in the CountryRepository class, not the generic base class.

Upvotes: 2

Related Questions