EF核心查询通过过滤进行多对多查询

时间:2020-03-18 14:34:01

标签: c# entity-framework linq .net-core entity-framework-core

我具有以下表格结构:

enter image description here

我想检索提供的 reportId 的所有资金。 我是这样做的:

                var result = _context.FundsInReports
                        .Join(_context.Funds,
                                a=> a.FundId,
                                b => b.Id,
                                (fir, fund) => new {fir, fund})
                        .Join(_context.Reports,
                                a=> a.fir.ReportId,
                                b=> b.Id,
                                (fir2, report) => new { fir2, report})
                        .Where(q=> q.fir2.fir.ReportId==reportId)
                        .Select(res => new FundsResponse()
                        {
                            FundId = res.fir2.fund.Id,
                            LegalName = res.fir2.fund.LegalName,
                            HeaderName = res.fir2.fund.HeaderName,
                            PortfolioCurrency = res.fir2.fund.PortfolioCurrencyId,
                            BaseCurrency = res.fir2.fund.BaseCurrencyId,
                            FileName = res.fir2.fund.FileName,
                            Locked = res.fir2.fund.Locked

                        }).ToList();

这很好用... 但是,我想使用以下代码:

                var result = _context.Funds
                    .Include(a => a.FundsInReports)
                    .ThenInclude(a => a.Report)         // Many to many , intellisense is not working here !
                    .Select(res => new FundsResponse()
                    {
                        FundId = res.Id,
                        LegalName = res.LegalName,
                        HeaderName = res.HeaderName,
                        PortfolioCurrency = res.PortfolioCurrencyId,
                        BaseCurrency = res.BaseCurrencyId,
                        FileName = res.FileName,
                        Locked = res.Locked

                    }).ToList();

但是我不知道如何在此代码中添加过滤(位置)。 谢谢...

1 个答案:

答案 0 :(得分:1)

您不要在自定义投影中使用“包含”。它们是产生结果的替代方法。因此,只需运行

var result = _context.FundsInReport
    .Where( fr => fr.ReportId == someId )
    .Select(fr => new FundsResponse()
    {
        FundId = fr.Fund.Id,
        LegalName = fr.Fund.LegalName,
        HeaderName = fr.Fund.HeaderName,
        PortfolioCurrency = fr.Fund.PortfolioCurrencyId,
        BaseCurrency = fr.Fund.BaseCurrencyId,
        FileName = fr.Fund.FileName,
        Locked = fr.Fund.Locked
    }).ToList();