EF4将where子句添加到where子句中

时间:2016-06-07 10:13:19

标签: c# entity-framework 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()
    select new
    {
        doc.ID,
        JobSheetId = jobSheets.DocumentID,
        doc.Name,
        doc.DateCreated,
        doc.StoreID,
        StoreName = doc.Store.Name,
        DocumentType = doc.DocumentType.Name,
        doc.DocumentTypeID,
        HelpDeskFaultStoreName = hs.Store.Name,
        DocStoreName = doc.Store.Name,
        PPMScheduleLinesStoreName = ppmScheduleLines.Store.Name,
        PIR = invoice.PurchaseInvoiceReference
    });


    fileDocuments = fileDocuments.Where(x => x.PIR == jobSearchParams.PIR);

生成的where子句如下所示:

WHERE ([Extent2].[fld_str_PIR] = @p__linq__0) OR (([Extent2].[fld_str_PIR] IS NULL) AND (@p__linq__0 IS NULL))

我不明白它为什么要添加IS NULL子句。

2 个答案:

答案 0 :(得分:1)

它会添加它们,因为您的NumGlyphs可能为null。如果它为null,EF将假定您要返回jobSearchParams.PIR为空的行。但在sql中,使用" ="无法与null进行比较。操作者:

fld_str_PIR

这就是为什么它会为你处理这种情况并为这两种情况生成正确的查询 - 无论WHERE ([Extent2].[fld_str_PIR] = @p__linq__0) -- doesn't work if @p__linq__0 is null 是否为空。

答案 1 :(得分:0)

经过大量搜索后,我发现另一篇文章突出显示了UseDatabaseNullSemantics设置:

context.Configuration.UseDatabaseNullSemantics = true;

启用此设置后,我的查询将在900毫秒内运行,而不是超时。