将SQL (Left Outer Join's)转换为LINQ

本文关键字:转换 LINQ SQL Left Outer Join | 更新日期: 2023-09-27 18:02:19

我有麻烦转换多个LEFT OUTER JOIN到LINQ的Oracle Sql查询。我的尝试没有返回预期的结果。有人可以帮助转换SQL查询下面的LINQ。

string currentCulture = Culture.GetCulture();
string query = @"SELECT *
               FROM CTGLBL g, CTTGLBL ct, CTLANG lang
               WHERE g.sysctglbl = ct.sysctglbl(+) AND 
                     ct.sysctlang = lang.sysctlang (+) AND
                     NVL(lang.activeflag, 1)= 1 AND
                     (ISOCODE LIKE '" + currentCulture + "%' OR ISOCODE IS NULL)";

ISOCODE属于CTLANG表。

p。我不能使用像LINQPAD或Linqer这样的工具。

将SQL (Left Outer Join's)转换为LINQ

但是对于sql(这里转换为linq)来说,更好的做法是使用join来连接表,而不是使用where:

string currentCulture = Culture.GetCulture();
var result = from g in CTGLBL
             join ct in CTTGLBL on g.sysctglbl equals ct.sysctglbl into ctj
             from ct in ctj.DefaultIfEmpty()
             join lang in CTLANG on ct.sysctlang equals lang.sysctlang into langj
             from lang in langj.DefaultIfEmpty()
             where (lang == null ?  1 : (lang.activeflag ?? 1)) == 1 &&
                 (lang?.ISOCODE.StartsWith(currentCulture) || lang?.ISOCODE == null)
             select new { g, ct, lang };

您也可以像这样为您的CTLANG添加"nested select":

string currentCulture = Culture.GetCulture();
var result = from g in CTGLBL
             join ct in CTTGLBL on g.sysctglbl equals ct.sysctglbl into ctj
             from ct in ctj.DefaultIfEmpty()
             join lang in CTTGLBL.Where(lang => lang.activeflag ?? 1 == 1 &&
                                                  (lang.ISOCODE.Contains(currentCulture) ||
                                                   lang.ISOCODE == null))
             on ct.sysctlang equals lang.sysctlang into langj
             from lang in langj.DefaultIfEmpty()
             select new { g, ct, lang };

(我看到的是左连接,不是右连接)

假设你的模式中表之间有适当的关系,使用SQL server (Linq TO SQL)这将工作,不确定它是否支持Oracle:

string currentCulture = Culture.GetCulture();
var data = from g in db.CTGLBL
           from ct in g.CTTGLBL.DefaultIfEmpty()
           from lang in g.CTLANG.DefaultIfEmpty()
           where !g.CTLANG.Any() || 
                 ( lang.activeflag == 1 &&
                   lang.ISOCODE.StartsWith(currentCulture))
           select new {g, ct, lang};