项目Linq查询结果到复杂对象

时间:2013-06-03 20:57:26

标签: c# linq entity-framework

我正在尝试将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 = ????
                };

是否可以一步完成?

1 个答案:

答案 0 :(得分: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成为List<T>,则可以使用.ToList()包裹该部分。