Question

I mapped some of my code as follows inside service layer:

var authors = _repository.FindAll().Where(x => x.IsActive == 1).ToList();
authorViews = authors.ModelToViewModelCollection();

But my senior advised me to map as follows inside repository layer:

return (from c in Context.Books
                    .Where(x=>x.IsActive == 1)
                    select new BookDetailsView
                    {
                        ID = c.ID,
                        TitleB = c.TitleB,
                        TitleE = c.TitleE,

                    }).ToList();

What is the difference between both.

Was it helpful?

Solution

The main difference is that in the first case, a controller (or a service) will directly manipulate EF to build the query . That's not the repository pattern no matter how you write it.

The second approach keeps the EF manipulation inside the repository and returns directly the view model, thus the upper layer doesn't know you're using EF and doesn't have to build a query.

The purpose of the Repository is to decouple other layers from persistence i.e the other layers know only about the repository and deal only with objects specific to them. This way, the persistence can optimize how the objects are stored/retrieved without affecting the other layers. This means that you can use EF, Nhibernate, mongo db etc in you persistence according to what's best for the app and the business layer or the UI never know about it and never need to change when you change something in persistence.

If you wonder how many time you're switching db or changing persistence, switching db is very rarely, but changing persistence models (tables, columns etc) is very often, especially when developing. The repository helps you keep the changes only in the persistence.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top