在linq查询中概括where子句

时间:2016-06-06 13:09:36

标签: c# entity-framework linq entity-framework-4

我有以下linq查询:

    var fileDocuments = (
        from doc in fileUploads
        from invoice in
            (
                from inv in _dbContext.SupplierInvoiceHeaders
                where inv.InvoiceDocumentId == doc.ID || inv.JobSheetInvoiceId == doc.ID
                select inv
                ).DefaultIfEmpty()
        join pos in _dbContext.PurchaseOrders on invoice.PurchaseOrder.PurchaseOrderId equals pos.PurchaseOrderId into poss
        from po in poss.DefaultIfEmpty()
        join hdf in _dbContext.HelpDeskFaults on po.HelpdeskFaultId equals hdf.ID into hdfpo
        from hs in hdfpo.DefaultIfEmpty()
        join store1 in _dbContext.Stores on hs.StoreID equals store1.ID into hsf
        from hdfStore in hsf.DefaultIfEmpty()
        join js in _dbContext.JobSheets on invoice.SupplierInvoiceHeaderId equals js.SupplierInvoiceHeaderID into jss
        from jobSheets in jss.DefaultIfEmpty()
        join ch in _dbContext.ChildProjects on po.ChildProjectId equals ch.ID into chs
        from childProjects in chs.DefaultIfEmpty()
        join ph in _dbContext.ProjectHeaders on childProjects.ProjectHeaderID equals ph.ID into phs
        from projectHeaders in phs.DefaultIfEmpty()
        join ppmsl in _dbContext.PpmScheduleLines on projectHeaders.PPMScheduleRef equals ppmsl.ID into ppsmsls
        from ppmScheduleLines in ppsmsls.DefaultIfEmpty()
        join ss2 in _dbContext.Stores on ppmScheduleLines.StoreID equals ss2.ID into ssts
        from store2 in ssts.DefaultIfEmpty()
        where getJobWhereClause(invoice, hs, ppmScheduleLines, doc) 
        select new
        {
            doc.ID,
            JobSheetId = jobSheets.DocumentID,
            doc.Name,
            doc.DateCreated,
            doc.StoreID,
            StoreName = doc.Store.Name,
            DocumentType = doc.DocumentType.Name,
            doc.DocumentTypeID
        })
        .AsEnumerable()
        .Distinct()
        .Select(d => new JobDocumentDto
        {
            ID = d.ID,
            DocumentID = (d.JobSheetId) ?? d.ID,
            DocumentName = d.Name,
            DateCreated = d.DateCreated.ToString("dd/MM/yyyy"),
            StoreName = d.StoreName,
            DocumentTypeName = d.DocumentType,
            DocumentTypeId = d.DocumentTypeID
        }).OrderByDescending(x => x.ID);
    return fileDocuments;

我试图将where子句分成func:

    Func<SupplierInvoiceHeader, HelpDeskFault, PpmScheduleLineEntity, DocumentUploadEntity, bool> getJobWhereClause = (invoice, helpDeskFault, ppmScheduleLine, doc) =>
    {
        if (!string.IsNullOrEmpty(jobSearchParams.PIR) && string.IsNullOrEmpty(jobSearchParams.StoreName))
        {
            return invoice.PurchaseInvoiceReference == jobSearchParams.PIR;
        }
        if (string.IsNullOrEmpty(jobSearchParams.PIR) && !string.IsNullOrEmpty(jobSearchParams.StoreName))
        {
            return helpDeskFault.Store.Name.Contains(jobSearchParams.StoreName) || doc.Store.Name.Contains(jobSearchParams.StoreName) || ppmScheduleLine.Store.Name.Contains(jobSearchParams.StoreName);     
        }

        return invoice.PurchaseInvoiceReference == jobSearchParams.PIR && (helpDeskFault.Store.Name.Contains(jobSearchParams.StoreName) || doc.Store.Name.Contains(jobSearchParams.StoreName) || ppmScheduleLine.Store.Name.Contains(jobSearchParams.StoreName));
    };

我收到以下错误消息:

  

测试方法   IntegrationTests.Services.DocumentUploadServiceTests.Should_Search_By_PIR   抛出异常:System.NotSupportedException:LINQ表达式   节点类型&#39;调用&#39; LINQ to Entities不支持。

这是有道理的,因为没有从func到sql的直接转换,但有没有办法可以创建一个能够实现我目标的表达式?

1 个答案:

答案 0 :(得分:0)

最简单的方法就是使用扩展方法并返回IQueryable,就像这样(只需填写...):

public static IQueryable<fileUpload> FilterByThisStuff(this DbSet<fileUpload> db, ... invoice, ... helpDeskFault, ... ppmScheduleLine, ... doc)
{
    if (!string.IsNullOrEmpty(jobSearchParams.PIR) && string.IsNullOrEmpty(jobSearchParams.StoreName))
    {
        return db.Where(invoice=>invoice.PurchaseInvoiceReference == jobSearchParams.PIR);
    }
    if (string.IsNullOrEmpty(jobSearchParams.PIR) && !string.IsNullOrEmpty(jobSearchParams.StoreName))
    {
        return db.Where(...);     
    }

    return db.Where(...);
};

我注意到你那里有很多连接。考虑实际使用导航属性构建模型。在任何情况下,您可以像使用任何其他LINQ方法一样使用上面的内容,否则您将需要创建一些具体的类,以便您可以在扩展方法中使用它。简单的方法:

var results=db.FileUploads
  .FilterByThisStuff(a,b,c,d)
  .Select(...)
  .OrderBy(...)
  .Take(...);