【问题标题】:Linq In Clause & Predicate buildingLinq In 子句和谓词构建
【发布时间】:2011-02-20 21:40:40
【问题描述】:

我有两张桌子。 报告报告数据。 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> predicate, LLReportsDataContext reportDC) { if (reportDC == null) throw new 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));

【问题讨论】:

    标签: c# linq-to-sql predicatebuilder


    【解决方案1】:

    查询

    ReportDatas
    .Where( reportData => reportData.StartsWith( "Something%" ) &&
         reportData.Report.Id ==3)
    .Select( reportData => reportData.Report )
    .Distinct()
    

    关于LinqKit

    在使用 LinqKit 时,有时需要在实体集合中调用AsExpandable() 并编译谓词表达式。看这个例子:):how-to-use-predicate-builder-with-linq2sql-and-or-operator

    【讨论】:

    • 谢谢,这解决了我的问题。有一些小的调整。 var q = reportDC.ReportDatas .Where(predicate) .Select(reportData => reportData.Report) .Where(report => report.ServiceID.Equals(1)) .Distinct();
    猜你喜欢
    • 2017-03-21
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多