Search code examples
entity-frameworkarchitecturerepositoryrepository-patternpoco

Entity Framework, repository and Linq? Load just an entity or also child nodes?


I am new to Entity Framework and I want to get some points about the constellation EF, LINQ, POCOs and repositories.

We have a working solution with a repository which uses EF and POCOs to access the database. We are doing all our queries in LINQ through the context. We added the mapping into mapping classes which are loaded at the application start as the database/tables are already existing.

If I have a business case where I need to calculate for a specific company the amount of toys bought by the employees for their children.

How would I build up the repository / repositories?

A: call with one repository all employees of a company and then call in the service layer again another repo for every employee the children and so on?

B: call one repository which returns me the company with all employees, children and the toys?

A seems to me much cleaner and I can reuse the repositories more often. But B seams to be the more efficient but not reusable so much. Less repositories and the queries would get bigger and bigger.

That is just a small example... but we have much larger business cases. What is the best architectural approach in this case?

class Company
{
    List<Employee> employees;
}

class Employee
{
    List<Child> children;
}

class Child
{
    List<Toy> toys;
}

Solution

  • You don't need to call repository to get company, employee, children and toys!

    I need to calculate for a specific Company the amount of Toys bought by the employees for there children

    So your business case is to have a single number or maybe number per toy or number per employee. You don't need to load all those entities and compute it in your application. You just need to write an aggregation query (either in Linq or SQL). This whole computation is supposed to run in the database.

    If you need to hide the query behind the repository simply choose one where this business case belongs and expose the query as a new method for the repository.