我有两张桌子。 报告和 ReportData 。 ReportData有一个约束ReportID。
如何编写linq查询以返回ReportData满足谓词条件的所有Report对象? SQL中的这样的东西:
SELECT * FROM Report as r
Where r.ServiceID = 3 and r.ReportID IN (Select ReportID FROM ReportData WHERE JobID LIKE 'Something%')
这就是我构建谓词的方式:
Expression<Func<ReportData, bool>> predicate = PredicateBuilder.True<ReportData>();
predicate = predicate.And(x => x.JobID.StartsWith(QueryConfig.Instance.DataStreamName));
var q = engine.GetReports(predicate, reportsDataContext);
reports = q.ToList();
这是我目前的查询构建:
public override IQueryable<Report> GetReports(Expression<Func<ReportData, bool>> predicate, LLReportsDataContext reportDC)
{
if (reportDC == null) throw new ArgumentNullException("reportDC");
var q = reportDC.ReportDatas.Where(predicate).Where(r => r.ServiceID.Equals(1)).Select(r => r.Report);
return q;
}
我也尝试过以下操作: public override IQueryable GetReports(Expression&gt; predicate,LLReportsDataContext reportDC) { if(reportDC == null)抛出新的ArgumentNullException(“reportDC”);
var q = from r in reportDC.Reports
where r.ServiceID.Equals(1)
where r.ReportDatas.Where(predicate.Compile()).Select(x => r.ReportID).Contains(r.ReportID)
select r;
return q;
}
但是,我得到了这个异常:“用于查询运算符的不支持的重载'Where'。”
更新 这修好了它:
var q = reportDC.Reports.AsExpandable().
Where(r => r.ReportDatas.Any(predicate.Compile()))
.Where(r => r.ServiceID.Equals(1));
答案 0 :(得分:1)
ReportDatas
.Where( reportData => reportData.StartsWith( "Something%" ) &&
reportData.Report.Id ==3)
.Select( reportData => reportData.Report )
.Distinct()
使用LinqKit时,有时需要在实体集合中调用AsExpandable()
并编译谓词表达式。看这个例子:):how-to-use-predicate-builder-with-linq2sql-and-or-operator