Awkward Generic Repository Call

100 views Asked by At

I am implementing a generic repository pattern, I have done this quite a few times now but every time I do it there is something bugging me.

If I have a database design like below. (All the tables relate to one another.) And I make a call like the following

public IEnumerable<Domain> GetRealEstate()
{
     return _repository.GetAll();
}

enter image description here

I can get all the models from just that one call (The wonders of EF). The thing that bugs me is the fact that I have to say Domain in the method call, from the domain entity I will get all the relevant entity (Lazy loading) Companies etc. etc. It just feels wrong to use domain entity to get all the companies etc. etc. The repo pattern that I am using is a straight forward one.

Is there a better way of writing the methods so that it does not look so weird?

Below is sample code that i have

Controller

[RoutePrefix("api/realestate")]
    public class RealEstateController : ApiController
    {
        private readonly IRealEstateService _service;

        public RealEstateController(IRealEstateService service)
        {
            _service = service;
        }

        [Route("")]
        public Task<Domain> GetRealEstates()
        {
            var collection =  _service.GetRealEstate();
            return null;
        }

        [Route("{domainName}")]
        public Task<Domain> GetRealEstate(string domainName)
        {

        }
    }

Service

public class RealEstateService : IRealEstateService
    {
        private readonly IRealEstateRepository _repository;
        public RealEstateService(IRealEstateRepository repository)
        {
            _repository = repository;
        }
        public IEnumerable<Domain> GetRealEstate()
        {
            return _repository.GetAll();
        }
    }
1

There are 1 answers

0
Gert Arnold On

Sense & Responsibility.... This is a dilemma I see more people struggle with. I think the key to feeling easier about it is that Domain can be considered an aggregate root that encapsulates the whole object graph it's the owner of.

Let's look at a very common example that's closer than you might think, DbSet. DbSet is a repository. But I think most of us think it's totally acceptable, even good practice, to write a query like

context.Domain.Include(d => d.Companies)....

Nobody will say, what has a DbSet<Domain> to do with Company? Even when we add a Domain to the DbSet, and by doing that we add an entire object graph, nobody will feel any inclination to add each object through its "proper" DbSet. That would a totally useless hell of a job.

If this wasn't good practice, EF (or any ORM) wouldn't have navigation properties. Think of that... nightmare.