0

我正在尝试使用 linq Method-Expressions 编写一个(简单的)连接查询。虽然这对我来说似乎很正确,但生成的查询缺少 1 Join ...

表及其关系:

WorkingOrderTask n:1 WorkingOrder
WorkingOrder n:1 PurchaseOrderAV
PurchaseOrderAv 1:n Searchtag

所以,我想查询 all WorkingOrderTasks,它相关的地方PurchaseOrderAV有一定的Searchtag分配。

使用香草(我的)SQL,我会这样做:

SELECT 
    wot.Id AS WorkingOrderTaskId,
    wo.Id AS WorkingOrderId,
    poav.Id as PurchaseOrderAVId,
    s.*
FROM
    WorkingOrderTask wot
        INNER JOIN
    WorkingOrder wo ON wot.WorkingOrderId = wo.ID
        INNER JOIN
    PurchaseOrderAV poav ON wo.PurchaseOrderAvId = poav.Id
        INNER JOIN
    SearchTag s ON s.EntityPrimaryKey = poav.Id
WHERE
    s.KeyWord LIKE 'trucks%' AND
    s.EntityName = "PurchaseOrderAV";

试图在 Linq-Method-Expressions 中组装它,我想出了这个:

queryable = dbContext.WorkingOrderTask
        .Join(dbContext.WorkingOrder, wot => wot.WorkingOrderId, wo => wo.Id, 
            (wot, wo) => new { woId = wo.Id, wotId = wot.Id })
        .Join(dbContext.PurchaseOrderAV, jr => jr.woId, poav => poav.Id, 
            (jr, poav) => new { woId = jr.woId, wotId = jr.wotId, poavId = poav.Id })
        .Join(dbContext.SearchTag, jr2 => jr2.poavId, st => st.EntityPrimaryKey, 
            (jr2, st) => new { jr2.wotId, jr2.woId, jr2.poavId, st.GUID,st.EntityName, st.EntityPrimaryKey, st.EntityColumn, st.KeyWord })
    .Where(res =>
    res.EntityName == PurchaseOrderAV.EntityTypeStatic &&
    Like(res.KeyWord, searchTag))
    .Select(res => res.wotId);

但是,由 ef 生成的查询缺少一个连接(表WorkingOrder根本没有连接)加上它还连接Extent1`.`WorkingOrderId` = `Extent2`.`Idwhere Extend2is PurchaseOrderAv- 所以,一个错误的连接。:

SELECT 
    `Filter1`.`Id`
FROM
    (SELECT 
        `Extent1`.`Id`,
            `Extent1`.`WorkingOrderId`,
            `Extent2`.`Id` AS `ID1`
    FROM
        `WorkingOrderTask` AS `Extent1`
    INNER JOIN `PurchaseOrderAV` AS `Extent2` ON `Extent1`.`WorkingOrderId` = `Extent2`.`Id`
    WHERE
        `Extent1`.`WorkingOrderId` IS NOT NULL) AS `Filter1`
        INNER JOIN
    `SearchTag` AS `Extent3` ON `Filter1`.`ID1` = `Extent3`.`EntityPrimaryKey`
WHERE
    (`Extent3`.`EntityName` = 'PurchaseOrderAV')
        AND (`Extent3`.`KeyWord` LIKE 'trucks%')

(删除了不必要的列 linq 在每个范围内生成)

我很确定我在这里的 Method-Expression-Syntax 中做错了什么,但是我从头开始重写了 5 次,并且总是得到相同的错误结果。

我可以切换到 linq-query-syntax 或使用 StoredProcedure - 但我只是好奇这里出了什么问题。

编辑:写这篇文章有帮助:

    .Join(dbContext.WorkingOrder, wot => wot.WorkingOrderId, wo => wo.Id, 
        (wot, wo) => new { woId = wo.Id, wotId = wot.Id })
    .Join(dbContext.PurchaseOrderAV, jr => jr.woId, poav => poav.Id,

显然应该是

     .Join(dbContext.WorkingOrder, wot => wot.WorkingOrderId, wo => wo.Id, 
         (wot, wo) => new { woId = wo.Id, wotId = wot.Id, poavId = wo.PurchaseOrderAvId })
     .Join(dbContext.PurchaseOrderAV, jr => jr.poavId, poav => poav.Id, 
4

0 回答 0