[英]How to refactor a link query with filtering logic into a reusable method
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. 我正在使用EF Core来查询数据库,并且我的存储库类中有几个类似的查询,它们基于作为过滤器传递的值来过滤结果。
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).
(确切地说有12个字段)。
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)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.