假设我有以下方法,其中需要填充insuredNumber,但其余三个参数可能包含默认值,如下所示
方法签名:
public List<Portal_SurveyRecommendations> LoadSurveyRecommendations(string insuredNumber, string surveyLocationNumber, DateTime dateIssuedFilter, DateTime dateCompletedFilter)
{
}
默认值:
surveyLocationNumber = "-1"
dateIssuedFilter = DateTime.MinValue
dateCompletedFilter = DateTime.MinValue
如何在生成的Linq to Entites查询中忽略这些默认值?我已尝试过以下内容,但由于日期未正确过滤,因此返回的结果超出预期。
查询:
var surveys = ctx.Portal_SurveyRecommendations.
Where(c => c.CustNum.Equals(insuredNumber)).
Where(l => l.LocationKey.ToString().Equals(surveyLocationNumber)).
Where(di => di.DateRecIssued.Value > dateIssuedFilter || di.DateRecIssued.Value == null).
Where(dc => dc.DateRecComplete.Value > dateCompletedFilter || dc.DateRecComplete.Value == null).
OrderBy(o => o.ReportKey).ThenBy(o => o.RecNumKey).ToList();
我想我可以将查询分解为子查询,检查默认值但我有兴趣看看是否可以在一个语句中完成。
答案 0 :(得分:0)
你最好的办法是打破它:
var query = ctx.Portal_SurveyRecommendations
.Where(c => c.CustNum == insuredNumber);
if(surveyLocationNumber != -1)
query = query.Where(l => l.LocationKey == surveyLocationNumber);
if(dateIssuedFilter != DateTime.MinValue)
query = query.Where(di => di.DateRecIssued == null
|| di.DateRecIssued.Value > dateIssuedFilter);
if(dateCompletedFilter != DateTime.MinValue)
query = query.Where(dc => dc.DateRecComplete == null
|| dc.DateRecComplete.Value > dateCompletedFilter);
var surveys = query.OrderBy(o => o.ReportKey).ThenBy(o => o.RecNumKey).ToList();