3

我正在尝试将 EF 查询的结果投影到包含子集合的复杂对象上。目前我分两步执行此操作——首先查询,然后循环并创建投影。我想知道是否可以一步完成,但无法弄清楚创建子集合实例的语法。

当前代码:

var ctx = uow.Context;   

var invoices = from i in ctx.Invoices.Include(inv => inv.BatchInvoices.Select(imp => imp.ImportBatch))
                join bi in ctx.BatchInvoices on i.Id equals bi.InvoiceId
                join ib in ctx.ImportBatches on bi.ImportBatchId equals ib.Id
                select i;

var invoiceDTOs = new List<InvoiceDTO>();

foreach (Invoice invoice in invoices)
{
    var invoiceDTO = new InvoiceDTO
        {
            DocumentDate = invoice.DocumentDate,
            DocumentNumber = invoice.DocumentNumber,
            DueDate = invoice.DueDate,
            InvoiceId = invoice.Id
        };


    foreach (BatchInvoice batchInvoice in invoice.BatchInvoices)
    {
        var batchInvoiceDTO = new InvoiceDetailDTO
            {
                Current = batchInvoice.Current,
                Days1To30 = batchInvoice.Days1To30,
                Days31To60 = batchInvoice.Days31To60,
                Days61To90 = batchInvoice.Days61To90,
                DaysOver90 = batchInvoice.DaysOver90,
                RunDate = batchInvoice.ImportBatch.FileGeneratedDate
            };
        invoiceDTO.InvoiceDetails.Add(batchInvoiceDTO);
    }
    invoiceDTOs.Add(invoiceDTO);
}

这是我卡住的地方:

var invoices2 = from i in ctx.Invoices.Include(inv => inv.BatchInvoices.Select(imp => imp.ImportBatch))
            join bi in ctx.BatchInvoices on i.Id equals bi.InvoiceId
            join ib in ctx.ImportBatches on bi.ImportBatchId equals ib.Id
            select new InvoiceDTO
                {
                    DocumentDate = i.DocumentDate,
                    DocumentNumber = i.DocumentNumber,
                    DueDate = i.DueDate,
                    InvoiceId = i.Id,
                    InvoiceDetails = ????
                };

是否可以一步完成?

4

1 回答 1

3

当然,您可以在 Linq 查询中使用 Linq 查询。尝试这个:

var invoices2 = 
    from i in ctx.Invoices.Include(inv => inv.BatchInvoices.Select(imp => imp.ImportBatch))
    join bi in ctx.BatchInvoices on i.Id equals bi.InvoiceId
    join ib in ctx.ImportBatches on bi.ImportBatchId equals ib.Id
    select new InvoiceDTO
    {
        DocumentDate = i.DocumentDate,
        DocumentNumber = i.DocumentNumber,
        DueDate = i.DueDate,
        InvoiceId = i.Id,
        InvoiceDetails = 
             from b in i.BatchInvoices
             select new InvoiceDetailDTO
             {
                 Current = b.Current,
                 Days1To30 = b.Days1To30,
                 Days31To60 = b.Days31To60,
                 Days61To90 = b.Days61To90,
                 DaysOver90 = b.DaysOver90,
                 RunDate = b.ImportBatch.FileGeneratedDate
             }
    };

如果你真的需要InvoiceDetails成为 a List<T>,你可以只用 a 包裹那部分.ToList()

于 2013-06-03T21:05:20.010 回答