Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Repository pattern - selecting specific fields of the entity for EF performance reasons

So, I am having a hard time with this Repository pattern. In lots of articles, posts and etc. I read that the repository should return only database objects(no DTOs, no mappers inside the repository).So you return single database object or list of objects.

This is OK, but for EF(entity framework) performance reasons, it's OK to return only field's that you need, not the entire entity.

So, how are you supposed to do that with repository pattern? You cannot select the database object with specific fields because it is detached (ctx.Users.Select(new User(){ properties }).FirstOrDefault()) , you cannot return an anonymous object, and as I read it's not good practice to return IQueryable<User> and outside the repository to select desired fields.

Can you share some practice?

like image 291
Gamaboy Avatar asked Sep 02 '25 07:09

Gamaboy


1 Answers

We solved it with 2 types of generic functions. You can either use

  • Automapper ProjectTo, which will define the mapping based on the generic type.
  • Write a custom selector expression to return an anonymous object. (You can return anonymous objects if you pass it on and return the same generic, that's also what the Select method's signature looks like)

In both cases the repository doesn't return the entity anymore, but it's also not responsible for for the transformation of the object, instead the Automapper library, or the caller with the select expression are taking care of that.

like image 153
peter Avatar answered Sep 04 '25 20:09

peter