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

时间:2016-08-12 09:10:30

标签: c# sql oracle linq

我无法将具有多个LEFT OUTER JOIN的Oracle Sql查询转换为LINQ。我的尝试没有返回预期的结果。有人可以帮助将下面的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表。

PS。我不能使用LINQPAD或Linqer等工具。

2 个答案:

答案 0 :(得分:2)

但是对于你的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 };

您还可以为"nested select"添加CTLANG,如下所示:

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 };

答案 1 :(得分:2)

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

假设您的架构中的表与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};