简体   繁体   中英

EF Core Query Many to Many with filtering

I have the following table structure:

在此处输入图片说明

I want to retrieve all funds for provided reportId . I did it this way:

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

and this works fine... However, I would like to use this code:

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

but I don't know how to add filtering (where) into this code. Thanks...

You don't use Include with custom projections. They are alternative approaches to generating results. So just run

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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