简体   繁体   English

Linq在子句和谓词中的构建

[英]Linq In Clause & Predicate building

I have two tables. 我有两张桌子。 Report and ReportData . 报告ReportData ReportData has a constraint ReportID. ReportData具有约束ReportID。

How can I write my linq query to return all Report objects where the predicate conditions are met for ReportData? 如何编写linq查询以返回满足ReportData谓词条件的所有Report对象? Something like this in SQL: 在SQL中是这样的:

SELECT * FROM Report as r
Where r.ServiceID = 3 and r.ReportID IN (Select ReportID FROM ReportData WHERE JobID LIKE 'Something%')

This is how I'm building my predicate: 这就是我构建谓词的方式:

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();

This is my query construction at the moment: 这是我目前的查询构造:

    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;
    }

I've tried doing the following as well: public override IQueryable GetReports(Expression> predicate, LLReportsDataContext reportDC) { if (reportDC == null) throw new ArgumentNullException("reportDC"); 我也尝试过以下操作:公共重写IQueryable GetReports(Expression>谓词,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;
    }

However, I get the this Exception: "Unsupported overload used for query operator 'Where'." 但是,出现以下异常:“查询运算符'Where'使用了不受支持的重载。”

UPDATE This fixed it: 更新此修复它:

        var q = reportDC.Reports.AsExpandable().
            Where(r => r.ReportDatas.Any(predicate.Compile()))
            .Where(r => r.ServiceID.Equals(1));

Query 询问

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

AboutLinqKit 关于LinqKit

When using LinqKit, sometimes you need to call AsExpandable() in the entity collection and to compile the predicate expression. 使用LinqKit时,有时您需要在实体集合中调用AsExpandable()并编译谓词表达式。 see this example : ): how-to-use-predicate-builder-with-linq2sql-and-or-operator 参见以下示例:)如何使用linq2sql和和或运算符来谓词生成器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM