I am using EF Core to query the database and I have several queries like this in my repository class to filter the result based on the values passed as filters.
if (!string.IsNullOrEmpty(queryObj.JobBoard))
query = query.Where(j => j.JobBoard.JobBoardName.Contains(queryObj.JobBoard));
if (!string.IsNullOrEmpty(queryObj.Division))
query = query.Where(j => j.Division.Contains(queryObj.Division));
if (!string.IsNullOrEmpty(queryObj.City))
query = query.Where(j => j.City.Contains(queryObj.City));
if (!string.IsNullOrEmpty(queryObj.State))
query = query.Where(j => j.State.StateName.Contains(queryObj.State));
is there away to implement a reusable method so I don't have to repeat this for every field? (there are 12 fields to be exact).
Well, I don't think so because in this case, you are not just accessing the first-order object in every case. In some cases you're checking against properties on those objects.
Try out this. Include all the other properties with && operator.
query = query.Where(j =>
string.IsNullOrEmpty(queryObj.JobBoard) ? true : j.JobBoard.JobBoardName.Contains(queryObj.JobBoard)
&& string.IsNullOrEmpty(queryObj.Division) ? true : j.Division.Contains(queryObj.Division)
&& string.IsNullOrEmpty(queryObj.City) ? true : j.City.Contains(queryObj.City)
&& string.IsNullOrEmpty(queryObj.State) ? true : j.State.StateName.Contains(queryObj.State)
);
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.