Question

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

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?

if possible can you please tell me of a more suitable way to do the sorting?

Was it helpful?

Solution

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.

If you want to prevent misuse (e.g. code injection), then instead pass an enum (or string) (containing the sortby parameter) to the service and have your service build the query accordingly.

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.

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