简体   繁体   English

使用存储库和服务层在EF中排序

[英]Sorting in EF with Repository and a Service Layer

I have a couple of classes that implement a common repository interface, one of the methods in these classes is a method that returns a Paged Result and takes a 我有几个实现公用存储库接口的类,这些类中的一种方法是返回Paged Result并采用

Expression<Func<T, bool>> OrderBy

I have also created a Service Layer that will use the repository classes, as i have read it's not preferred to send an Expression object from UI To Service Layer, so i decided to send it as a parameter, if i send it as string which contains the name of the parameter how can i convert the string to be as a property to be used in an Expression Object, for example suppose i have an Entity called User and i send to the method a parameter called "UserName", how can i convert "UserName" to be turned into a "UserName" property which can be used in the Expression> OrderBy object? 我还创建了一个将使用存储库类的服务层,因为我已阅读过从UI到服务层发送Expression对象的方法,因此我决定将其作为参数发送(如果我将其作为包含以下内容的字符串发送):参数的名称,我如何将字符串转换为要在表达式对象中使用的属性,例如,假设我有一个名为User的实体,并且向该方法发送了一个名为“ UserName”的参数,该如何转换将“ UserName”转换为可以在Expression> OrderBy对象中使用的“ UserName”属性?

if possible can you please tell me of a more suitable way to do the sorting? 如果可以的话,能否请您告诉我一种更合适的分类方法?

Instead of receiving Expression<Func<T, bool>> your service could receive Func<IQueryable<T>, IQueryable<T>> which is more flexible (enables any LINQ, not just where) and doesn't require the additional work that Expressions do. 您的服务可以接收Func<IQueryable<T>, IQueryable<T>> ,而不是Expression<Func<T, bool>> Func<IQueryable<T>, IQueryable<T>>它更灵活(可以在任何LINQ上启用,而不仅仅是在任何地方),并且不需要其他工作表达式可以。

If you want to prevent misuse (eg code injection), then instead pass an enum (or string) (containing the sortby parameter) to the service and have your service build the query accordingly. 如果要防止滥用(例如代码注入),请改为将枚举(或字符串)(包含sortby参数)传递给服务,并让您的服务相应地构建查询。

I hope that by UI you are not referring to the actual UI, but instead to a VM or a controller and that your views are not aware of anything below them. 我希望通过UI您不要指的是实际的UI,而是指VM或控制器,并且您的视图不知道它们下面的任何内容。

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

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