crazydev
crazydev

Reputation: 575

How to implement a generic method in Repository to make joins in linq

Hello I have a linq query that makes several joins on tables and which eventually returns me a single row.

For the time being, I have used the generic method GetAll() that returns the single row.

The query that I have written is as follows:

from h in _repositoryWorkers.GetAll()
join p in _repositoryJobs.GetAll() on h.Id equals p.THI_N_ID
join q in _repositoryHome.GetAll() on h.Id equals q.THI_N_ID

    public Repository()
    {
        this.context = new WorkersContext();
        entities = context.Set<T>();
    }
    public IEnumerable<T> GetAll()
    {

            return entities.AsEnumerable<T>();

    }

What I want to achieve is the following as an example:

from w in repo.Query<Worker>()
join e in repo.Query<XEntity>() on ...

I do not want to use a List that returns me only a single row. I just want to return an object of this row.

Please advise.

Upvotes: 2

Views: 470

Answers (1)

Steve
Steve

Reputation: 1316

In isolation, I would write something like:

var result = context.Worker()
    .Include(worker => worker.XEntity)
    .Where(worker => worker.ID == id)
    .SingleOrDefault();

result will either be the single Worker entity with XEntity populated or null if there is no entry with a matching id.

How do you make it generic though?

I've tried a lot of things over the last few years and in the end, I find that specific methods work best. So I'll have a generic base repository for the simple stuff but then I'll extend that when I need to do things like this.

So I would have a specific repository for the Worker entity that extends the generic base. It would have a method like:

public Worker GetByIdWithXEntity(id)
{
    this.Queryable()
        .Include(worker => worker.XEntity)
        .Where(worker => worker.ID == id)
        .SingleOrDefault();
}

(Queryable is a protected method on the base repository)

This approach is a bit of a pita with large projects but I've found that it works very nicely as it keeps all the data access logic in the Repo, it makes unit testing your services simple and it's very clear exactly what's going on.

That said, if anyone has a better way, I'd love to hear it!

Upvotes: 3

Related Questions