简体   繁体   中英

Dynamic query in EF using Expression

I am trying to understand what is the best way to create a dynamic query.

I have a requirement where I will be writing an API to retrieve data from DB. the API has lot of filter paramters. eg. I need to retrieve movies that can be filtered on following properties.

MovieName, Genere, Rating, Language, Category

I can give these parameters in any combination.. so in my Data layer I started framing my dynamic query like this.

IQueryable<Movie> qryContext = null;

if(.string.isnullorEmpty(request.MovieName)) qryContext = context.Movies.Where(x => x.MovieName == request.MovieName)

if(.string.isnullorEmpty(request.Genere)) qryContext = context.Movies.Where(x => x.Genere == request.Genere)

if(.string.isnullorEmpty(request.Language)) qryContext = context.Movies.Where(x => x.Language == request.Language)

if(.string.isnullorEmpty(request.Category)) qryContext = context.Movies.Where(x => x.Category == request.Category)

if(qryContext.= null) return qryContext;ToList(); else return null;

Based on the given parameters, the sql query is framed..


But When I search in google reg dynamic queries in EF, most of the links refer to using Expression. Do I need to make use of Expression or can I proeeed with the above method.

Also let me know what advantage I get on using expressions.

Basically what you see inside the Where(...) is expression. In your example this would be x => x.Language == request.Language

if(!string.isnullorEmpty(request.Language)) qryContext = context.Movies.Where(x => x.Language == request.Language)

Also, I would recommend you to take a look into the Dynamic expression library from EF Plus team. Here https://dynamic-linq.net/basic-simple-query

This allows you to pass expression as a string. And you can construct your filters in the Frontend, and pass them as a string, which helps you to write a much cleaner implementation of filters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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