简体   繁体   English

使用存储库模式 - 出于EF性能原因选择实体的特定字段

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

So, I am having a hard time with this Repository pattern. 所以,我在使用这个Repository模式时遇到了困难。 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. 在很多文章,帖子等中,我读到存储库应该只返回数据库对象(没有DTO,存储库中没有映射器)。因此,您返回单个数据库对象或对象列表。

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. 这没关系,但是对于EF(实体框架)性能原因,只返回您需要的字段,而不是整个实体。

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. 你不能选择具有特定字段的数据库对象,因为它是分离的( ctx.Users.Select(new User(){ properties }).FirstOrDefault() ),你不能返回一个匿名对象,而且当我读到它时,这不是一个好习惯。返回IQueryable<User>并在存储库外部选择所需的字段。

Can you share some practice? 你能分享一些练习吗?

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. Automapper ProjectTo,它将根据泛型类型定义映射。
  • 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) (如果传递匿名对象并返回相同的泛型,则可以返回匿名对象,这也是Select方法的签名的样子)

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. 在这两种情况下,存储库不再返回实体,但它也不负责对象的转换,而是Automapper库,或者具有select表达式的调用者正在处理它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM