使用多个字段上的联接和合并将 SQL 转换为 LINQ 查询时出现问题

问题描述 投票:0回答:1

我正在尝试将以下 SQL 语句转换为 EF Core Linq 查询,该查询将利用带有 Coalesce 的 Join om 多个字段 (??)。

var query2 = from t1 in _dbContext.table1
    join t2 in _dbContext.table2
        on new { t1.SiteId, t1.DepartmentId } 
        equals new { SiteId = t2.SiteId ?? t1.SiteId, DeptID = t2.DeptId ?? t1.DepartmentId }
    where t1.Id == request.Id && t2.UserID == request.userId 
        && (t2.IsRestricted == 1 ? t1.CreatedBy == t2.UserID : t2.UserID == request.userId)
    select t1;

问题是合并(??)运算符后的 equals new {} 中的 t1.references 给出了以下错误

名称“ti”不在“equals”右侧的范围内。考虑交换“等于”两侧的表达式。

这是我要转换的SQL语句

SELECT DISTINCT
    t1.*
FROM 
    table1 t1
INNER JOIN
    table2 t2
ON
    t1.SiteId = COALESCE(t2.SiteId, t1.SiteId)
AND
    t1.DepartmentId = COALESCE(t2.DeptID, t1.DepartmentId)
WHERE
    (t1.Id = @Id) AND (t2.UserID = @USERID) AND (CASE t2.IsRestricted WHEN 1 THEN t1.CreatedBy ELSE @USERID END = t2.UserID)

有什么建议吗?谢谢

linq join entity-framework-core coalesce
1个回答
0
投票

使用 EF Core 文档中所述的另一种联接语法集合选择器在 where 子句中引用外部

var query2 = 
    from t1 in _dbContext.table1
    from t2 in _dbContext.table2
        .Where(t2 => t1.SiteId == t2.SiteId ?? t1.SiteId && t1.DepartmentId == t2.DeptId ?? t1.DepartmentId)
    where t1.Id == request.Id && t2.UserID == request.userId 
        && (t2.IsRestricted == 1 ? t1.CreatedBy == t2.UserID : t2.UserID == request.userId)
    select t1;
© www.soinside.com 2019 - 2024. All rights reserved.